Javascript: How to append childs to section element? - javascript

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.

Related

How use JavaScript to query on selector result properly?

I have the following piece of HTML.
<div id="outer"><b class="dest">something</b>
<div id="test"><b class="dest">unwanted stuff</b></div>
</div>
Let's say I already have a reference to the outer element with document.querySelector("#outer"). How can I query all b elements with the dest class and are the first child of its parent? I tried document.querySelector("#outer").querySelector("b.dest") and document.querySelector("#outer").querySelector("b.dest:first-child") but only the first b element has returned. How can I get both b elements (through the result of document.querySelector("#outer"))?
.querySelector only selects one element max.
.querySelectorAll Returns an array-like node list.
You want:
var bElements = document.getElementById("outer").querySelectorAll('b.dest:first-child');
This will return an array of all elements that:
Have a parent with an id of outer
have the class dest
are the first-child of their parent
Then you can access each element just like an array, ex.
bElements[0]
DEMO:
var bElements = document.getElementById("outer").querySelectorAll('b.dest:first-child');
console.log(bElements)
<div id="outer"><b class="dest">something</b>
<div id="test"><b class="dest">unwanted stuff</b></div>
</div>

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

About querySelector() with multiple selectors

I had a situation in which I wanted to focus either an input tag, if it existed, or it's container if it didn't. So I thought of an intelligent way of doing it:
document.querySelector('.container input, .container').focus();
Funny, though, querySelector always returns the .container element.
I started to investigate and came out that, no matter the order in which the different selectors are put, querySelector always returns the same element.
For example:
var elem1 = document.querySelector('p, div, pre');
var elem2 = document.querySelector('pre, div, p');
elem1 === elem2; // true
elem1.tagName; // "P".
My question is: What are the "reasons" of this behavior and what "rules" (if any) make P elements have priority over DIV and PRE elements.
Note: In the situation mentioned above, I came out with a less-elegant but functional solution:
(document.querySelector('.container input') ||
document.querySelector('.container') ).focus();
document.querySelector returns only the first element matched, starting from the first element in the markup. As written on MDN:
Returns the first element within the document (using depth-first
pre-order traversal of the document's nodes|by first element in
document markup and iterating through sequential nodes by order of
amount of child nodes) that matches the specified group of selectors.
If you want all elements to match the query, use document.querySelectorAll (docs), i.e. document.querySelectorAll('pre, div, p'). This returns an array of the matched elements.
The official document says that,
Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.
So that means, in your first case .container is the parent element so that it would be matched first and returned. And in your second case, the paragraph should be the first element in the document while comparing with the other pre and div. So it was returned.
That's precisely the intended behavior of .querySelector() — it finds all the elements in the document that match your query, and then returns the first one.
That's not "the first one you listed", it's "the first one in the document".
This works, essentially, like a CSS selector. The selectors p, div, pre and pre, div, p are identical; they both match three different types of element. So the reason elem1.tagName == 'P' is simply that you have a <p> on the page before any <pre> or <div> tags.
You can try selecting all elements with document.querySelectorAll("p.a, p.b") as shown in the example below and using a loop to focus on all elements that are found.
<html>
<body>
<p class="a">element 1</p>
<p class="b">element 2</p>
<script>
var list=document.querySelectorAll("p.a, p.b");
for (let i = 0; i < list.length; i++) {
list[i].style.backgroundColor = "red";
}
</script>
</body>
</html>

How will i able to get the DOM position of the character

HTML
<div id="board">
<div>ab X</div>
<div>a <span class='target'>V</span> b</div>
<div>Xab</div>
<div>
I wanted to access the DOM place of V in my HTML and alert V, I must not use $('#board').eq(1).text().charAt(2). I need its DOM position so that I can easily trace the span that is wrapping the V.
THIS is not working, What's the right way?
alert($('#board').eq(1).eq(2).text());
This is the original problem, i can get someone who can help me so im trying to revised it How will i get the span class id under which the text belongs?
ALGORTIHM:
1. Found V from row looping and y looping
2. Find the span where it belongs to
Assuming span elements that have V text content should be selected, you can use .filter() method:
var $span = $('#board span').filter(function() {
return (this.textContent || this.innerText) === 'V';
});
Getting index of selected element:
$span.index();
Index of the V character within the text content of span's parent element:
var vIndex = $span.parent().text().indexOf('V');
Note that jQuery returns a jQuery-wrapped array of the selected elements, as you are using ID selector, the returned collection has only one wrapper/top-level selected element:
Object[div#board]
.eq(1)(just like getting an element by index from a simple array) returns the second top-level selected element that doesn't exist in the collection. Apart from that chaining .eq() methods in that way doesn't make any sense as it returns only one element.

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