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;
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;
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'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
I'm trying to load X amount of <li>'s into a <ul> via a for loop in a jquery function, and while I think I've got the syntax about right I'm not getting anything loading. (no problem with loading a single <li>, but none for multiples with the method I've tried)
Initially I attempted to pass a variable into the loop to determine the amount of increments: var peekListAmount = 5;
That didn't work so I went for a bog-standard loop incrementer. That doesn't work either so, after searching here and getting close, I have put together a fiddle to see if someone can point out what I'm doing wrong: http://jsfiddle.net/janowicz/hEjxP/8/
Ultimately I want to use Knockout.js to dynamically input a number to pass to the loop amount variable, but 1st things 1st.
Many thanks in advance.
When you do:
var peekListItem = $('<li>...</li>');
you're creating a single instance of an <li> node, encapsulated in a jQuery object.
Appending an already-present node to the DOM just removes it from its current place in the DOM tree, and moves it to the new place.
You need to create the node inside the loop, not outside, otherwise you're just re-appending the same node each time, not a copy of that node.
In fact, given you're not manipulating that node, you can just put the required HTML directly inside the .append() call without wrapping it in $(...) at all:
$(function() {
var peekList = $('<ul class="peekaboo-list">').appendTo('div.peekaboo-wrap');
function addLiAnchorNodes(nodeAmount) {
var html = '<li>' +
'<p class="peekaboo-text"></p></li>';
for (var i = 0; i < nodeAmount; ++i) {
peekList.append(html);
}
}
addLiAnchorNodes(5);
});
See http://jsfiddle.net/alnitak/8xvbY/
Here is you updated code
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
var peekListItem = '<li><p class="peekaboo-text"></p></li>';
//var peekListAmount = 5;
var tmp = '';
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
tmp += peekListItem;
}
peekList.append(tmp);
$('div.peekaboo-wrap').append(peekList); // This bit works fine
}
addLiAnchorNodes();
});
This should work. Instead of appending the list item in each loop, append the list only once at the end.
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
peekList.appendTo('div.peekaboo-wrap');
var addLiAnchorNodes = function (nodeAmount){
var list = "";
for (var i = 0; i < 10; i++){
list += '<li>Sample<p class="peekaboo-text"></p></li>';
}
peekList.append(list);
}
addLiAnchorNodes();
});
Here is the updated fiddle
Try this:
$(function(){
var peekList = $('<ul class="peekaboo-list"></ul>');
$(peekList).appendTo('div.peekaboo-wrap'); // This bit works fine
var addLiAnchorNodes = function (nodeAmount){
//var nodeAmount = peekListAmount;
for (var i = 0; i < 10; i++){
var peekListItem = $('<li><p class="peekaboo-text"></p></li>');
peekListItem.appendTo(peekList);
}
}
addLiAnchorNodes();
});
I am trying to store an array of objects in an array by going through each paragraph element in a div container with the .get() method. I try to access the attribute with .attr() but it doesn't seem to work. How would I modify this code in order to be able to access the 'id' attribute of each message?
var messages = $("#message_container p").get();
var idstest = [];
for (int i = 0; i < messages.length; i++){
idstest.push(messages[i].attr("id"));
}
I think it has to do with some fundamental incompatibility with .get() and .attr(). When I 'alert' the objects provided by .get() I get [object HTML---]. I'm assuming that is not the form necessary in order to use .attr?
get will give you the DOM element. These are NOT jquery objects so you can't use attr on them. There's no reason to use get at all here.
var messages = $("#message_container p");
var idstest = [];
messages.each(function(){
idstest.push($(this).attr("id"));
});
http://jsfiddle.net/ujdeH/
EDIT: You also can't use int.
If for some reason you did want to use get to get the raw DOM elements, you would then just use .id:
http://jsfiddle.net/ujdeH/1/
var messages = $("#message_container p").get();
var idstest = [];
for (var i = 0; i < messages.length; i++) {
idstest.push(messages[i].id);
}
try instead:
var idstest = [];
$("#message_container p").each(function(i){
idstest.push($(this).attr("id"));
});
Just wanted to add the $.map shortcut: http://jsfiddle.net/UuWq3/.
var idstest = $.map(messages, function(elem) {
return $(elem).attr("id");
});
$.map returns a new array based on the original array (or jQuery object). The array returned is constructed with the function you pass (in this case, messages is transformed by the function such that each element is replaced with it's ID).
You should wrap the object in jQuery container:
$(messages[i]).attr("id")
Actually no need for jQuery here, this pure JavaScript will work just fine on all browsers:
var idstest = [];
var container = document.getElementById("message_container");
if (container) {
var messages = container.getElementsByTagName("p");
for (var i = 0; i < messages.length; i++) {
idstest.push(messages[i].id);
}
}
jQuery is all good and powerful, but if you can achieve the same task with short/easy enough pure JS then why not?
This said, if all your existing code is jQuery then you might be better off sticking with it (using the code from other correct answers here) just for sake of consistency and readability.