get firstChild of div - javascript

I am trying to get the text of the span element. I have tried two methods using querySelectorAll and getElementByClassName but both give me the error "Uncaught TypeError: Object # has no method 'getElementsByTagName'" how do I go about getting the text of the span element?
javascript
var interstitial;
// 1st attempt
interstitial = document.querySelectorAll('div.top_bg').getElementsByTagName("span");
// 2nd attempt
interstitial = document.getElementByClassName('top_bg')[0].getElementsByTagName("span");
if (interstitial) {
console.log(interstitial[0].firstChild.innerHTML);
}
html
<div class="top_bg">
<span style="font-size:14px;line-height:30px">The text I am trying to get.</span>
</div>

Include the span in the query
interstitial = document.querySelectorAll('div.top_bg span');
document.querySelectorAll('div.top_bg') returns a collection so you'll have to select a node then apply getElementsByTagName
Also its getElementsByClassName not getElementByClassName notice the Elements
http://jsfiddle.net/dRvDt/1/

You are getting the error because the object returned by querySelectorAll is a NodeList, and NodeLists don't have a getElementsByTagName method. You should do something like:
var node, nodeList, spans
if (document.querySelectorAll) {
nodeList = document.querySelectorAll('div.top_bg');
node = nodeList[0];
if (node) {
spans = node.getElementsByTagName('span');
}
}
spans is now a NodeList of the spans contained in the first element of the first NodeList, if there was one. The first one will be at spans[0], and so on.

if you can use the jquery, you can look for the span html easy:
$("div.top_bg>span").firstChild().html();

Related

Get all elements containing a class with querySelector

For changing some styles in a class I'm using querySelector():
el.querySelector('.fa fa-car').style.display = "none";
This works fine for one element but if there are more elements containing this class and I want to change the display to none for all of them, this command only deletes the first occurrence of it leaving the next ones untouched.
I tried to do it with querySelectorAll():
el.querySelectorAll('.fa fa-car').style.display = "none";
But this one returns an error message:
html2canvas: TypeError: Cannot set property 'display' of undefined
any ideas about how to get all the elements containing a specific class and perform an operation on them?
The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Use Document.querySelectorAll() to get all the elements. Then use forEach() to set the style in each element:
var elList = document.querySelectorAll('.fa.fa-car');
elList.forEach(el => el.style.display = "none");
Please Note: Some older version of IE (<8) will not support querySelectorAll(). In that case use
Array.from(document.querySelectorAll('.fa.fa-car'))
querySelectorAll() returns a collection of elements. To change their styling you need to loop through them.
Also note that your selector appears to be invalid. Given the FontAwesome class rules I presume you need to select by both classes. Try this:
Array.from(el.querySelectorAll('.fa.fa-car')).forEach(function() {
this.style.display = "none";
});
Alternatively, as you've tagged the question with jQuery, you could just simplify all that to just:
$('.fa.fa-car').hide();
querySelector only select one element, to select all element you can use querySelectorAll
[].map.call(el.querySelectorAll('.fa fa-car'), n => { n.style.display = 'none'; })
Use method querySelectorAll()
See https://www.w3schools.com/jsref/met_document_queryselectorall.asp
You are getting error because querySelectorAll returns an array.Iterate over it and then use style.display
You could do all your operation by iterating the occurence of this class and of course by help of some if clauses.
$('.fa.fa-car').each(function(){
$(this).css('color','white');
})

DOM manipulation - Center H1 element using javascript

How can I center my h1 using javascript?
h1 is <h1>Instrument track Recommendations</h1>, I tried below and it does not work.
var centeredH1 = document.getElementsByTagName("h1");
centeredH1.style.textAlign = "center";`
I know it would work with an ID using document.getElementById("h1id"); if I had one but I don't have an ID to work with.
getElementsByTagName returns an array-like object. If you have only one element, it will return an array-like object with one element. You need to get the [0] indexed element in that object. But as you have mentioned, it will be better to work with id in this case, if you want to attach styles only to one element.
var centeredH1 = document.getElementsByTagName("h1")[0];
// -------------------------------------------------^^^
centeredH1.style.textAlign = "center";
<h1>Test</h1>
DEMO
JAVASCRIPT
var h1s = document.getElementsByTagName("h1");
h1s[0].style.textAlign="center";
HTML
<h1>
THIS IS TO BE CENTERED
</h1>
You need to access first element from array returned by javascript getElementsByTagName

Javascript: How to append childs to section element?

Assuming that I have the following HTML:
<body>
<section role="main">
</section>
</body>
1) Can I do this?
var section = document.getElementsByTagName("section");
2) Can I do this?
var section = document.querySelector("section[role=main]");
3) And finally, how can I append childs to this element? appendChild() doesn't work.
var p = document.createElement("p").innerText("A paragraph.");
section.appendChild(p);
You can use either 1 or 2,
Using getElementsByTagName -
check out the fiddle - http://jsfiddle.net/2jzho6hh/3/
this one returns an array of all elements with tag name section, so to access the first section element you have to use the 0 index on the array. For the second element use 1 index on the array and so on..
Using querySelector,
check the fiddle - http://jsfiddle.net/2jzho6hh/2/
querySelector returns first element matching the selector you have specified as in this case section[role=main] which means select the first sectionelement with attribute role and its value being main
There is also one other method querySelectorAll which is, you may think, a union of above two methods. It selects elements on the basis of CSS selector syntax just like querySelector does and it returns an array of all elements matching the selector just like the getElementsByTagName
Correct code is
var p = document.createElement("p");
p.innerHTML="A paragraph";
section.appendChild(p);
don't add innerHTML at the time of declaring p.If you do so p will not return child node.Declare p as a node and then add innerhtml to it.

querySelectorAll doesnt do anything

Why i cant get this extremly simple script to work. It works with querySelector, but not with querySelectorAll
HTML
<p id="log2"></p>
<script type="text/javascript" src="dom.js"></script>
JS
var q = document.querySelectorAll("#log2").innerHTML+="<p>qwerty</p>";
querySelectorAll returns a NodeList (which is like an array), not a single HTMLElement.
You need to either grab the first element from it ([0]) or loop over it.
There is no point in using All with an ID selector since IDs must be unique.
<p class="log2"></p>
<p class="log2"></p>
<p class="log2"></p>
<script>
var nodes = document.querySelectorAll(".log2");
for (var i = 0; i < nodes.length; i++) {
nodes[i].innerHTML+="<p>qwerty</p>";
};
</script>
document.querySelectorAll returns a NodeList of elements (i.e. multiple elements).
To pick up the first element use either document.querySelectorAll("#log2")[0], or document.querySelector("#log2").
In your case you are trying to get an element by ID, which should be only one element on the page. Hence, you may use cross browser method document.getElementById("log2") instead.

How to select text by tag name in element?

I need to select title which is in div wrapped by h2, so i do something like this this.getElementsByTagName('h2') where this is current div in which is h2 - it returns current h2 element, but when i trying to get innerHTML or innerText it return null. What am I doing wrong?
it returns current h2 element, but when i trying to get innerHTML or innerText it return null. What am I doing wrong?
getElementsByTagName returns a NodeList, not an element. The list doesn't have innerHTML, but each of its elements does, e.g.:
var list = this.getElementsByTagName('h2');
if (list[0]) {
title = list[0].innerHTML;
}
Or if you're sure that it will exist:
title = this.getElementsByTagName('h2')[0].innerHTML;
...but that will throw an exception if there are no h2's found.
No, this.getElementsByTagName('h2') returns an array of elements with tag name h2.
You have to iterate the array and access the correct element you want.
Two things:
You should capture the first element of the node list that's returned by getElementsByTagName():
var h2 = this.getElementsByTagName('h2')[0];
Different browsers use different properties to retrieve the tag contents:
var title = h2.textContent || h2.innerText || null;
Yes, you have done a small mistake. Because , this.getElementByTagName('h2') will return you a list ( of tags).
Being your tag is the first element as [0]
you can use
var v= this.getElementsByTagName('h2');
var yourdata=v[0].innerHTML;
As the other answers state getElementsByTagName returns an array.
Another option would be to use querySelector (supported only by modern browsers so check what you need to support first)
Running querySelector on this page gives the following:-
window.document.querySelector('h1').innerHTML //#>
"How to select text by tag name in element?"
querySelector
querySelectorAll

Categories