$.get("http://en.wikipedia.org/wiki/Afghanistan", function(response) {
var elements = $.parseHTML(response);
var wiki = $(elements).find('#mw-content-text').find("p");
var ps = [];
var arrayLength = wiki.length;
for (var i = 0; i < arrayLength; i++) {
if (wiki[i].innerHTML === "") {
break;
}
var item = wiki[i]
ps.push(item);
$("#fakediv").append(ps);
}
I am trying to remove the links from the variable item, but I can't seem to find any examples of how to do this from a variable - everything assumes that I'll be using a selector.
I've tried .removeAttr("href"), but that doesn't seem to work and I'm not quite sure how to remove links and leave the text.
You say you want to unlink the links, but you are looping over paragraph elements and trying to remove its attribute. I doubt the paragraph has an href attribute.
So you need to find the anchors inside the paragraph tags
var item = wiki.eq(i);
item.find("a").removeAttr("href")
ps.push(item);
or
var item = wiki.eq(i);
item.find("a").contents().unwrap();
ps.push(item);
Related
newbie javascript question. I made sure to research as much as I could before posting here, I've tried many solutions but could be searching for the wrong thing.
I've attached an image below of the issue I have. I'm trying to retrieve everything in the dark blue boxes, but I can't identify those input tags as there is nothing unique about them, I can however identify their parent divs by the class 'f-active'. When the divs have that class they have been selected by the user which is what I am interested in.
My attempt so far
var divArray = document.querySelectorAll('div.add-filter.f-active');
var arr = [];
for(var i=0; i < divArray.length; i++){
var childArray = divArray[i].children;
// console.log(childArray);
for(var i=0; i < childArray.length; i++){
if(childArray[i].tagName == "INPUT"){
var catNameCollection = arr.push(childArray[i].name);
// console.log(catNameCollection);
}
}
}
I tried to use a for loop to get all the parents, then use another for loop to select the children (input tags) and then grab the name attribute, however it is just outputing numbers. I did originally try to create 'divArray' as document.querySelectorAll('div.add-filter.f-active').children, but this and then grab the name attribute in the for loop, but this didn't return anything at all.
Any help anyone could offer would be greatly appreciated, I'd love to know what I'm doing wrong.
Thank you!
Your i is same for both loops. Use:
var divArray = document.querySelectorAll('div.add-filter.f-active');
var arr = [];
for(var i=0; i < divArray.length; i++){
var childArray = divArray[i].children;
// console.log(childArray);
for(var k=0; k < childArray.length; k++){
if(childArray[k].tagName == "INPUT"){
var catNameCollection = arr.push(childArray[k].name);
// console.log(catNameCollection);
}
}
}
Classic for-loops usually aren't the best tool for iterating through DOM elements - they add a lot of clutter and are error-prone, especially when you have to nest them.
In your case it'd be simpler to instead modify your query to directly grab all input elements with a div.f-active parent, then extract the names by iterating through them with a forEach. For example (using ES6 or higher):
const arr = [];
// Get list of all <input> elements that have <div> element parents with class f-active.
const nodes = document.querySelectorAll('div.add-filter.f-active > input');
// Extract name from each input element matched by your selector.
nodes.forEach(node => arr.push(node.name));
Or if you're stuck using ES5:
var arr = [];
var nodes = document.querySelectorAll('div.add-filter.f-active > input');
nodes.forEach(function(node) {
arr.push(node.name);
});
Here's a quick JSFiddle I put together to demonstrate the concept for you. (You'll need to open the console to see the result)
Hopefully that helps :)
I am trying to clear some (10 of 50) fields by selecting elements by their shared id. The problem is that I can only select one at a time with getElementById()
Here is the jsFiddle demonstrating the single element grab. jsFiddle
function toggleBankCount() {
secBankFields = document.getElementById('2ndBankFields');
secBankFields.value = '';
}
I am fairly certain I can do what I want with getElementsByName() which returns an array of elements. However, I am using Perl and the name of the elements must be different in order for %fdat to work properly on submit. Can you help me?
Here's how you can do it:
toggleBankCount = function () {
secBankFields = document.getElementsByTagName('input');
for (var i = 0; i < secBankFields.length; ++i) {
if(secBankFields[i].id === '2ndBankFields')
secBankFields[i].value = '';
}
}
though ids should be unique, consider using classes instead. Also, classes and ids shouldn't begin with a digit.
Check it out: JSFiddle
There are some Javascript functions which should help you.
Get element by ID attribute
Id should be unique.
var elm = document.getElementById("some_id");
Get elements by Tag name
// get all div elements
var elms = document.getElementsByTagName("div");
Get element by Class attribute
// get all elements with class .some_class
var elms = document.getElementsByClassName("some_class");
Get element by Name attribute
// get all elements with attribute name some_name
var elms = document.getElementsByName("some_name");
Get element by CSS selector
var elms = document.querySelectorAll("div.box, span.title");
for (var i = 0; i < elms.length; i++) {
var elm = elms[i];
console.log(elm);
}
I'm trying to remove or replace characters in an element while using appendChild as follow:
var options = from.getElementsByTagName("option");
var to = document.getElementById("target");
to.appendChild(options[i].replace("(A)",""));
I tried various different syntax but no luck. Can someone help? Either JQuery or javascript works for me.
Thanks
I assume you're already in a for loop. If so, use the .text property of the option element, and create a new text node.
to.appendChild(document.createTextNode(options[i].text.replace("(A)","")));
Or better, in the loop append to a string, and create a single node at the end.
var txt = "":
for (var i = 0; i < options.length; ++i)
txt += options[i].text.replace("(A)"), "");
}
to.appendChild(document.createTextNode(txt));
If you actually wanted to append a copy of the element itself, then use .cloneNode(true) instead.
for (var i = 0; i < options.length; ++i) {
var clone = to.appendChild(options[i].cloneNode(true));
clone.text = clone.text.replace("(A)", "");
}
I have an array of class names that I want to search a page for. Then I'd like to find all those elements, grab the text inside, and append it to a div.
var div = document.createElement('div');
div.innerHTML = 'List of names from this page';
document.body.appendChild(div);
var classNameArray = ['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'];
for (var i = 0; i < classNameArray.length; i++) {
element = classNameArray[i];
getSuggestedAuthors(element);
function getSuggestedAuthors(element) {
var classes = document.getElementsByClassName(element);
var index;
for (var index = 0; index < classes.length; index++) {
var class = classes[index];
var textInsideClass = class.innerHTML;
div.appendChild(textInsideClass);
}
}
}
When I run this, it gives me:
Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.
I believe the problem is occuring at var textInsideClass = class.innerHTML, because when I remove that, it simply grabs all the classes and appends them to the div. However, I'd like to only get the text inside the class.
Anyone know how to do this without jQuery? I'm injected this hs through Google Chrome's executeScript injection.
Thanks so much!
I think your issue is that appendChild only works with nodes. You might be better off just appending to innerHTML using something along the lines of a.innerHTML += f.innerHTML.
You should also be sure to move the getSuggestedAuthors function out of the loop. It works ok as it is, but it's much better form not to declare functions inside a loop.
If you only need to support chrome then all of the handy methods on the Array.prototype should exist :)
var a = document.createElement('div');
a.innerHTML = 'List of names from this page';
document.body.appendChild(a);
function getSuggestedAuthors(elements) {
for (var d = 0; d < elements.length; d++) {
a.appendChild(document.createTextNode(elements[d].innerText));//append loop items text to a
}
}
['user', 'username', 'fullname', 'profile-field', 'author', 'screen-name'].map(function(cls) {
return document.getElementsByClassName(cls);
}).forEach(getSuggestedAuthors);
I've read a billion questions like this, but never found an answer yet.
Anyway, when I type
var variableContainingID = "header";
var div = $("#"+variableContainingID);
It returns 'undefined'
But when I type
var variableContainingID = "header";
var div = $('[id^="'+variableContainingID+'"]');
It works fine.
Any ideas why?
UPDATE
var json = '{"divs":['
var children = $(".parent_container > div");
var idArray = [];
var numArray = [];
for (var x=0; x<children.length; x++) {
var eleid = $(children[x]).attr("id");
idArray.push('"'+eleid+'"');
numArray.push(x+1);
}
var idString = idArray.join(",");
var numString = numArray.join(",");
json += idString;
json += '],"number":['+numString+']}';
var obj = JSON.parse(json);
for (x in obj["divs"]) {
var div = $('[id^="'+obj["divs"][x]+'"]');
}
Do you think the double quotes could be throwing it off?
As you wrote in your question:
var div = $("#"+variableContainingID);
var div = $('[id^="'+variableContainingID+'"]');
These two lines are not identical. The first one, will select an element with id of header. The second one,
selects elements that have the specified id with a value beginning exactly with a given string (header).
So if you have an element like this:
<div id="headerHere"></div>
The first one ($("#"+variableContainingID)) can't select it, but the second one ($('[id^="'+variableContainingID+'"]')) can select that element.
This is because you used ^= in your selector. See jQuery API: Attribute Starts With Selector (name^="value").
It's worth to see all attribute selectors in jQuery.
Attribute Selectors in jQuery