Reputation: 1873
first of all i should say that it's my first day of learning java script.
Basically i'm trying to create chrome extention which will add dummy button after search bar button in "google.com".
So far i've written this code:
var x = document.getElementsByName("btnK");
if (typeof x[0] === 'undefined' || x[0] === null) {
} else {
parent = x[0].parentElement;
button = document.createElement("button");
parent.appendChild(button);
}
As you can see i'm getting google's search button, then getting parent of it and add button as last to it. The issue here is that after i'm creating this button it can't be modified in any way.
As i understand i can't change style or text of newly created element, only elements that was already defined when form was loading. So, knowing this information i want to ask(my question is below)
Question: Is there any way to insert button, created in html code into my script?
Note: I understand it might be easy and trivial question, and i'm sorry that i couldn't find clear and right answer just by googling, so far i'm kind of confused with javascript
Edit: After comment i need to clearify one thing. I can't use any of code to the button after createElement
, it has no effect, so basically i need to create it with style already deined somehow
Edits: Thanks all for the suggestion in comments, here what i've tried so far:
1st approach:
As was suggested, i just straight copy button "search", change it a bit and readded to parent. I hoped to see three buttons now, but it's just redrawed search button in new position, here's the code:
x[0].value = "test"
parent.appendChild(x[0]);
2nd approach:
Create button, then get it and change, also not working, here's the code:
button.id = "dummyId"
parent.appendChild(button);
var styledButton = document.getElementById("dummyId");
styledButton.value = "test";
It changed the value if i'm looking at this button in "inspect element", but visually it's empty
Guys, sorry, it was my stupidity. It just that value
field doesn't change text !!! And also i needed to create input, not value
So, final soultion:
input = document.createElement("input");
input.type = "submit"
input.value = "test"
parent.appendChild(input);
Sorry again
Upvotes: 0
Views: 114
Reputation: 1871
When you create the button, you can add, add text, classes, event listeners etc.
button = document.createElement("button");
button.id = 'my-new-button';
button.textContent = 'Click me';
button.classList.add('my-button');
button.addEventListener('click', function() {
alert('clickie');
});
Demo: https://jsfiddle.net/ubmb6p3f/1/
Upvotes: 1