Reputation: 4008
I want to query over all in a selected container.
container = document.querySelector('[data-container]')
I also have a variable
that contains a value.
If the child elements have a value
attribute (like inputs)
child.value = variable
If not, like 'p', 'div' use:
child.innerHTML = variable
How do I check the element/type attribute?
Do I need to check tag by tag, or is something more general ?
Upvotes: 1
Views: 50
Reputation: 1075209
You can use something more general: in
: It checks to see if a property exists on an object (or its prototypes):
if ("value" in element) {
// use value
} else {
// Use innerHTML or textContent, etc.
}
Example:
var container = document.querySelector("[data-container]");
var children = container.children;
for (var n = 0; n < children.length; ++n) {
var element = children[n];
var hasValue = "value" in element;
console.log(element.tagName, hasValue ? "has value" : "doesn't have value");
}
<div data-container>
<p>Paragraph</p>
<input type="text">
</div>
Upvotes: 2