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
Related
I'am working on a bot that will edit some form on website, one part of the form is where is some html. I copy data from the converting to HTMLCollection do some actions, and then i want to save it back to the . And in case to do so i need to convert HTMLCollection object back to a string.
How i get and convert the data:
var htmlFromTextArea = document.getElementById('nameOfTextArea').value;
var htmlObject = document.createElement('div');
htmlObject.innerHTML = htmlFromTextArea;
var htmlElements = htmlObject.getElementsByTagName("*")
And now i need htmlElements to become string again
I tried the following but it seems not working:
var stringWithHtmlTobeSavedInTextArea = htmlElements.text;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.textContent;
or
var stringWithHtmlTobeSavedInTextArea = htmlElements.innerText;
Yes, htmlElements is HTMLCollection. So seperate each element and add outerHTML of element to string using loop.
var htmlObject = document.createElement('div');
htmlObject.innerHTML = "<a>anchor</a><p>paragraph</p>";
var htmlElements = htmlObject.getElementsByTagName("*");
var stringWithHtmlTobeSavedInTextArea="";
for (i = 0; i < htmlElements.length ; i++){
stringWithHtmlTobeSavedInTextArea += htmlElements[i].outerHTML;
}
console.log(stringWithHtmlTobeSavedInTextArea);
Please note that, above solution is not correctly working in case if the HTML inside div element is like <div><a>anchor</a></div>
So It is better to use innerHTML or get actual text from <textarea> eg.
var stringWithHtmlTobeSavedInTextArea = htmlObject.innerHTML;
//Or
var stringWithHtmlTobeSavedInTextArea = htmlFromTextArea;
$.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);
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 have been trying to get the text from a div using only javascript.
I started with jQuery using the following code:
var divText = $("div.Xr3").html();
Then for my JavaScript I tried:
var divText = document.getElementsByClassName("Xr3").innerHtml;
Which returns undefined. How can I accomplish this using JavaScript only?
getElementsByClassName returns a live array of HTML elements, so you can't access innerHTML directly like this. You will either have to loop over its results, or if you know there's only one, apply [0] to it before accessing innerHTML.
var divTexts = [];
var divs = document.getElementsByClassName("Xr3");
var numDivs = divs.length;
while (var i = 0; i < numDivs; i++) {
divTexts.push(divs[i].innerHtml);
}
or, in a single-element scenario,
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
If Xr3 is used one time, you can use
var divText = document.getElementsByClassName("Xr3")[0].innerHtml;
I am working on a project in Google Blogger. First i want to explain a thing.
In blogger every post that is created has a unique id assigned to it by blogger itself. This id can be retrieved using Blogger JSON. So i have retrieved the ids of four recent posts using JSON.
I want to wrap these first four id containers around a DIV container using JQuery or Javascript.
The problem is when i use these ids absolutely in the selector $ and use the wrapAll() function the id container's gets wrapped up. But as i said i'm using JSON to get the container id's so the values of ID's are stored in variable's and when i use those variable as selection for wrapAll() function it doesn't work.
I have demos of both those situation's which can be seen by going to this blog http://youblog-demo.blogspot.com/ and using the firebug console to run these code.
Situation 1 when i use absolute container ids
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
$("#3337831342896423186,#123892177945256656,#9095347670334802803,#2525451832509945787").wrapAll('<div>');
}
};
Situation 2 when i use variable's to select the containers
var script = document.createElement("script");
script.src = "http://youblog-demo.blogspot.com/feeds/posts/default?alt=json&callback=hello";
document.body.appendChild(script);
function hello(json){
if(json.feed.entry.length>4){
var post_num=4;
var id_coll = new Array();
var front_name = "#";
for(i=0; i<post_num; i++){
var ids = json.feed.entry[i].id.$t;
var post_id = ids.substring(ids.indexOf("post-"));
var only_id = post_id.substring(5);
id_coll[i] = only_id;
}
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
}
};
So when i use the situation 2 code then it doesn't work but the situation1 code works fine. Can anybody help me with this
You need to pass in the selector as a string, not a list of arguments;
$(joined_id_0+', '+joined_id_1+', '+joined_id_2+', '+joined_id_3).wrapAll('<div>');
Or even better, replace all of:
var joined_id_0 = String.concat(front_name,id_coll[0]);
var joined_id_1 = String.concat(front_name,id_coll[1]);
var joined_id_2 = String.concat(front_name,id_coll[2]);
var joined_id_3 = String.concat(front_name,id_coll[3]);
$(joined_id_0,joined_id_1,joined_id_2,joined_id_3).wrapAll('<div>');
With:
$('#'+id_coll.join(', #')).wrapAll('<div>');
And remove the line: var front_name = '#';
You have to concatenat the ids, separated by a comma, as in #id1, #id2, ....
You can do that this way:
[joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')
The whole line:
$([joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',')).wrapAll('<div>');
If it doesn't works, check the what is returned by [joined_id_0,joined_id_1,joined_id_2,joined_id_3].join(',') (alert() it, or use console.log).