chrome extension insert text issue - javascript

http://www.w3schools.com/js/js_statements.asp
i wrote a chrome extension to change the content of intro class but it is not working??
i have created a division and inserted it before intro class
the code is written in content.js
var div=document.createElement("div");
div.innerText='test123';
document.getElementsByClassName("intro").insertBefore(div,document.getElementsByClassName("intro")childNodes[0]);

getElementsByClassName returns a NodeList. As such, it has no such method as insertBefore.
If you want to insert your div inside all elements of class intro, you can accomplish this via a loop:
var elements = document.getElementsByClassName("intro");
for(var i = 0; i < elements.length; i++){
var div = document.createElement("div");
div.innerText = 'test123';
elements[i].insertBefore(div, elements[i].childNodes[0]);
}
Alternatively, if there is only one element, you can do:
var div = document.createElement("div");
div.innerText = 'test123';
document.getElementsByClassName("intro")[0].insertBefore(div, document.getElementsByClassName("intro")[0].childNodes[0]);

Related

I want to display multiple elements from a loop into the Document by its just showing the last element the user input instead showing everything

<body>
<div id = "app">TODO... This is an HTML5 Template. Put your own content here.</div>
<script>
var Para = prompt("How many paragraph elements you want?");
var element;
for(i = 0; i < Para; i++){
element = prompt("Provide the element you want to fill up the Paragraph above");
}
document.getElementById("app").innerHTML = element;
</script>
</body>
You should be doing something like this:
document.getElementById("app").insertAdjacentHTML('beforeend', element);
As stated by #Makyen, you shouldn't be using innerHTML += as I stated in my first answer. That would probably create issues in your application, please follow the link in the comments to get more information.
And probably, the line of code I wrote should be inside the for loop.
for(i = 0; i < Para; i++){
element = prompt("Provide the element you want to fill up the Paragraph above");
document.getElementById("app").insertAdjacentHTML('beforeend', element);
}

Wrap a div element for a body's innerHTML

I need to wrap up the body content inside a div dynamically. I tried the below code and i am getting, 'newDiv.append function is undefined'. I tried with setTimeout as well and checked after the jquery file loads made for loop to get loaded. Still getting the same error.
function initiate() {
var jq_script = document.createElement('script');
jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js');
document.head.appendChild(jq_script);
var newDiv = document.createElement('div')
newDiv.setAttribute('id', 'wrapper');
var bodyChildren = document.body.childNodes;
for (var i = 0; i < bodyChildren.length; i++) {
newDiv.append(bodyChildren[i]);
}
document.body.appendChild(newDiv);
}
initiate();
And i tried this as well to wrap up the body's innerHTML with a div element.
function initiate() {
var jq_script = document.createElement('script');
jq_script.setAttribute('src', '//code.jquery.com/jquery-1.11.2.min.js');
document.head.appendChild(jq_script);
var div = document.createElement("div");
div.id = "wrapper";
while (document.body.firstChild) {
div.appendChild(document.body.firstChild);
}
document.body.appendChild(div);
}
initiate();
This keeps on adding the wrapper element inside body. And the above script is inside iframe.
Any solution on this?
Two problems:
It's appendChild, not append.
Once that's out of the way, though, the other problem is in your loop: childNodes is a dynamic list, and so when you move a child out of body into newDiv, the list changes, making your indexes invalid.
You can fix that by just looping, moving first child into your div, until the body runs out of children, then append the div:
var newDiv = document.createElement('div')
newDiv.id = "wrapper"; // You don't need or want setAttribute here
var bodyChildren = document.body.childNodes;
while (bodyChildren.length) {
newDiv.appendChild(bodyChildren[0]);
}
document.body.appendChild(newDiv);
Or actually, you don't even need the list, you can use firstChild:
var newDiv = document.createElement('div')
newDiv.id = "wrapper"; // You don't need or want setAttribute here
while (document.body.firstChild) {
newDiv.appendChild(document.body.firstChild);
}
document.body.appendChild(newDiv);

How do you use Javascript to add or remove HTML/CSS code?

If I have a bunch of HTML code, similar to the following:
<div id='test0div'>
<p id='test0'></p>
</div>
How do I use JavaScript to add or remove more of those - i.e.
<div id='test1div'>
<p id='test1'></p>
</div>
<div id='test2div'>
<p id='test2'></p>
</div>
...etc.?
var container = document.createElement("div");
for(var i=0; i<5; i++) { // change i <5 as per your data source
var div = document.createElement("div");
var p = document.createElement("p");
p.id = "test"+i;
div.id = "test"+i+"div";
div.appendChild(p);
container.appendChild(div); // you can event append to particular id or body
}
// document.getElementById("divId").appendChild(container);
container, will have all the divs & p as you wish
This will give you the output you want. Just change the number of times the loop will execute based on your wish.
To remove you could use
$('#id').remove();
To add you could use
$("<div id='new'></div>").appendTo('#id');

How to access the programmatically generated elements using jQuery

How can I access a dynamically created element using jQuery? Suppose I have the following code:
for (var i = 0; i < count; i++)
{
var div = document.createElement("div");
div.setAttribute("id", "divHour" + i);
var button = document.createElement("button");
button.setAttribute("id", "btnHour" + i);
div.appendChild(button);
document.getElementById("divHours").appendChild(div);
}
How can I access the buttons using jQuery?
To select the button inside your original loop...
for (var i = 0; i < count; i++)
{
var div = document.createElement("div");
div.setAttribute("id", "divHour" + i);
var button = document.createElement("button");
button.setAttribute("id", "btnHour" + i);
div.appendChild(button);
document.getElementById("divHours").appendChild(div);
// moved after the button has been added to the DOM
// do something with the button in jQuery
$("#btnHour" + i).css({width:100})
}
As long as you know the HTML ID of the element. All you need to do is this:
$("#html_id")
jQuery uses CSS selectors.
Give the buttons a class:
div.setAttribute("class", "myButton");
Then you can get all of the buttons with
$('.myButton') ...
For example, to loop over them:
$('.myButton').each(function(){
console.log($(this).attr("id"));
});
If you want to identify each button, parse the number out of the class or give it a data-mynumber attribute and use $(this).data('mynumber')
var $button0 = $('#btnHour0')
var $button1 = $('#btnHour1')
// ... etc ...
Once you have cached the jQuery object, use it as you wish...
$button0.css({width: 400}).animate({width: 200})
EDIT
To access all buttons in a loop...
// assuming `count` is the same as the code used to create the buttons
for (var i = 0; i < count; i++){
var $button = $('#btnHour'+i)
// do stuff with $button here
}
EDIT
Alternatively, to access all button elements that have an ID that starts with btnHour
var $buttons = $('button[id^="btnHour"]')
// do stuff to all buttons here
$buttons.css({width:300})
var buttons=$('button[id^="btnHour"]');
Will give you the whole collection of buttons
Your question is extremely vague, I suspect you want to access a specific button contained within a div that user interacts with. More details are required as to what you want.
EDIT: following is how you can access the index of a button within a click handler.
var buttons=$('button[id^="btnHour"]').click(function(){
var buttonIndex= buttons.index(this);
var div=$('#divHour'+ buttonIndex)
/* can now interact with corresponding div*/
});
Another simpler way to find the parent div is :
$('button[id^="btnHour"]').click(function(){
var $parentDiv=$(this).parent()
})
To target a specific button use eq() method
var thirdButton=$('button[id^="btnHour"]').eq(2);/* indexing is zero based*/

Turn jQuery into vanilla JS - Insert p element after h1

Any ideas on how I would convert this jQuery to vanilla JS:
$('.section > h1').after('<p>This paragraph was inserted with jQuery</p>');
I am new to jQuery and even newer to vanilla JS.
This is as far as I got:
var newP = document.createElement('p');
var pTxt = document.createTextNode('This paragraph was inserted with JavaScript');
var header = document.getElementsByTagName('h1');
Not sure where to go from here?
jQuery does a lot for you behind the scenes. The equivalent plain DOM code might look something like this:
// Get all header elements
var header = document.getElementsByTagName('h1'),
parent,
newP,
text;
// Loop through the elements
for (var i=0, m = header.length; i < m; i++) {
parent = header[i].parentNode;
// Check for "section" in the parent's classname
if (/(?:^|\s)section(?:\s|$)/i.test(parent.className)) {
newP = document.createElement("p");
text = document.createTextNode('This paragraph was inserted with JavaScript');
newP.appendChild(text);
// Insert the new P element after the header element in its parent node
parent.insertBefore(newP, header[i].nextSibling);
}
}
See it in action
Note that you can also use textContent/innerText instead of creating the text node. It's good that you're trying to learn how to directly manipulate the DOM rather than just letting jQuery do all the work. It's nice to understand this stuff, just remember that jQuery and other frameworks are there to lighten these loads for you :)
You might find this function useful (I didn't test)
function insertAfter(node, referenceNode) {
referenceNode.parentNode.insertBefore(node, referenceNode.nextSibling);
}
Oh it's not so bad...
var h1s = document.getElementsByTagName('h1');
for (var i=0, l=h1s.length; i<l; i++) {
var h1 = h1s[i], parent = h1.parentNode;
if (parent.className.match(/\bsection\b/i)) {
var p = document.createElement('p');
p.innerHTML = 'This paragraph was inserted with JavaScript';
parent.insertBefore(p, h1.nextSibling);
}
}

Categories