0

I wish to add a new attribute to all of my elements that their type is text

Can you please let me know where I'm wrong?

Firstly, I identify all my elements that their type is text as follows (input tag name is the tag name that contains text types)

 var inputs = document.getElementsByTagName('input');

Secondly, I add my attribute to those with text type

if (inputs.type =='text') {var att = document.createAttribute("class")}

Then when I want to check if the new attribute is added or not

inputs.hasAttribute("class");

I got this error

Uncaught TypeError: inputs.hasAttribute is not a function

2 Answers 2

2
document.getElementsByTagName('input');

returns an array like list instead of just one element. Therefore, this is what you should do:

var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
    if(inputs[i].type == 'text'){
        inputs[i].classList.add("some", "class");
    }
}

An even better way would be this:

// Only works in recent browsers
document.querySelectorAll("input[type=text]").forEach(function(ele){
    ele.classList.add("some", "class");
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. what is some ? in your code. and how can I test if it works? because I tried your code and I got the same error.
inputs[i].classList.add("some", "class") means it's adding the class names some and class to the class list. inputs.hasAttribute("class") will give you an error because inputs as I said is a list, not an element.
1

Try this:

var inputs = document.getElementsByTagName("input");
for(var i = 0; i < inputs.length; i++){
    if(inputs[i].type == 'text'){
        var att = document.createAttribute("class");  
        att.value = "testClass";
        inputs[i].setAttributeNode(att);
        console.log(inputs[i].hasAttribute("class"));
    }
}
<input type="text"/>
<input type="text"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.