DOM manipulation - Center H1 element using javascript - 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

Related

Converting an Array of HTML Elements to Nodelist

I'm writing a function for swapping the position of child elements in a parent element.
<div class="parent">
<div class="first-child"></div>
<div class="second-child"></div>
</div>
So I'm getting the children of .parent turning the Nodelist into an array, reordering the array to swap the order / position of the elements i.e first-child, second-child becomes second-child, first-child - This all works perfectly. However, ideally the function will return the parent element with the reordered structure, but because I effectively spliced the nodelist into an array the elements in the array are no longer considered 'nodes' meaning I get an error when attempting to append it as a child to the parent.
So, how can I convert an array of elements back into a Nodelist as I understand that a Nodelist is not native to javascript?
Here's a Codepen of what I have so far. http://codepen.io/anon/pen/QNPKqB?editors=0011
Thanks!
The error in your code isn't that you need a NodeList, it's that you've named both a function and an element swap.
var parent = document.querySelector('.swap');
swap(parent, first, second);
Is what you need
I don't have a codepen account so instead, see the working code here:
https://jsfiddle.net/owr15hnf/
This is how you can convert HTML to node list,
const targetElement = document.getElementById('targetElement');
const htmlElementsArray = Array.from(targetElement.children).map(el => el.outerHTML)
// htmlElementsArray contains an array of HTML Elements.
console.log(htmlElementsArray,'ArrayList.')
const nodeList = new DOMParser().parseFromString([htmlElementsArray].join(''), "text/html").body.childNodes;
// nodeList is the converted Html list to node list
console.log(nodeList,'nodeList')
You can find the example here: https://codepen.io/furki911/pen/qByzdXm?editors=1111

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.

Is it possible to dynamically modify the style of a child element (with no id) in a div (with id)?

With the following code:
<div id="container">
<svg [attributes etc.]> ... </svg>
</div>
I would like to dynamically change the width and height of the SVG.
I have tried:
myObj = document.getElementById('container').getElementsByTagName('svg');
myObj.style.width = "400px";
but I get the error "undefined is not an object".
The SVG is loaded using a server-side include, and I can not modify it in any way, so I need to find a way to manipulate it from the outside.
I would prefer to avoid jQuery.
The reason you get that error is because myObj, the result of getElementsByTagName(), is a NodeList of elements since it can potentially return more than one element, and style is not defined on a NodeList. Not a particularly helpful error since it doesn't describe the actual problem...
Anyway, simply index off of that collection to get an element that you can work with:
myObj = document.getElementById('container').getElementsByTagName('svg');
myObj[0].style.width = "400px";
Alternatively, if you're sure you will only ever have one #container > svg, use querySelector() instead:
myObj = document.querySelector('#container > svg');
myObj.style.width = "400px";
getElementsByTagName returns the array-like collection object. So, you need to iterate over the collection for eg:
myObj = document.getElementById('container').getElementsByTagName('svg');
myObj[0].style.width = "400px";//myObj[0] refers to first found svg element
It may be possible to acheive this with css alone, providing you have access to that?
#container {
svg {
width: 400px;
}
}

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

Javascript: How to change a nodes name?

For example I have this HTML:
<body>
<div>Text</div>
</body>
And I would like to change the div to something else like p.
This is what I have tried but doesn't works:
var div = document.getElementsByTagName("div")[0]; // Get Element
div.nodeName = "p"; // Change It's Node Name to P
Please no libraries, and I don't really want to replace the actual div with a new p :)
You cannot just change an element. You have to create a new one. E.g.:
var div = document.getElementsByTagName("div")[0];
var p = document.createElement('p');
p.innerHTML = div.innerHTML;
div.parentNode.replaceChild(p, div);
But this could lead to invalid markup, if the original element contains nodes that cannot be descendants of the new node.
Reference: document.createElement, Node.replaceChild
Note: A better version (because it doesn't depend on serializing DOM to text and back and preserves attributes), can be found at https://stackoverflow.com/a/8584158/218196 .
The reason you can't just change the tagName property is because different HTML tags are actually different classes of objects. A div tag is an HTMLDivElement instance, a p tag is an HTMLParagraphElement instance, and so on. These classes can have vastly different properties and interfaces, so turning one into another is not as trivial as you'd think.
You can't.
As the MDC docs say:
nodeName is a read-only attribute.
You'll have to create a new element and give it the right content and attributes.
You cannot. The propery you're after is tagName, but it is read only. You would instead have to create a new node of the desired type, then transfer the innerHTML (and any other properties like className or style) to the new node. Then, insert the new node into the old node's parent, then remove the old node (or use replaceChild).
In other words, the long road is the only road.
I solved this in an XML scenario (eg. where there is no innerHTML) like so:
function renameNode (node, newNodeName) {
const newNode = node.ownerDocument.createElement(newNodeName);
Array.from(node.attributes).forEach(attr => newNode.setAttribute(attr.localName, attr.value));
Array.from(node.childNodes).forEach(childNode => newNode.appendChild(childNode));
node.parentElement.insertBefore(newNode, node);
node.parentElement.removeChild(node);
}
Does not return anything, but will update your DOM.

Categories