How would one reference document in a chrome background js script? [duplicate] - javascript

This question already has answers here:
How to access the webpage DOM/HTML from an extension popup or background script?
(2 answers)
Closed 1 year ago.
I've been trying to make an extension with chrome, but it seems like when I try to run this simple code:
function reddenPage() {
var bar = document.getElementsByClassName('nav rbx-navbar hidden-xs hidden-sm col-md-5 col-lg-4');
//console.log(bar[0].appendChild(bar[0].childNodes[2].cloneNode(true)));
if(bar[0]==null){
return false;
}else{
return true;
}
}
It returns :
Any help would be lovely, thank you so much!

As I understand You should do with :
document.querySelectorAll()
Example :
var x = document.querySelectorAll("h1, div");
You can't use .getElementByClassName() because getElementByClassName() only applies to single elements.
Different from querySelectorAll() which is flexible to select all variants of elements.
You will always find undefined if you use getElementsByClassName() for your case.
Example getElementsByClassName():
HTML:
<button class="btn btn-lg" onclick="reddenPage()">Click me</button>
<div class="same"></div>
<div class="same"></div>
<div class="same"></div>
Javascript:
function reddenPage(){
var x = document.getElementsByClassName('same');
console.log(x[0]);
if(x[0]==null){
alert("element found "+x.length);
}else{
alert("element found "+x.length);
}
}
Example queryselectorAll():
<button class="btn btn-lg" onclick="reddenPage_()">Click me</button>
<div class="diffrent-1"></div>
<div class="diffrent-2"></div>
<div class="diffrent-3"></div>
<div class="diffrent-4"></div>
Javascript:
function reddenPage_(){
var x = document.querySelectorAll('.diffrent-1, .diffrent-2, .diffrent-3, .diffrent-4');
console.log(x[0]);
if(x[0]==null){
alert("element found "+x.length);
}else{
alert("element found "+x.length);
}
}
Example getElementsByClassName() will return undefined:
function reddenPage_(){
var x = document.getElementsByClassName('diffrent-1 diffrent-2 diffrent-3 diffrent-4');
console.log(x[0]);
if(x[0]==null){
alert("element found "+x.length);
}else{
alert("element found "+x.length);
}
}
//Response undefined

Related

i can't make a button work, i've tried the eventListener and the onclick [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Javascript onclick function is called immediately (not when clicked)? [duplicate]
(1 answer)
Closed 9 months ago.
please if someone would be so kind and help me, i would be very happy, clearing i'm a beginner so help if you can, please.
the html
<div>
<h2>TO-DO LIST</h2>
<input type="text" id="tasks" class="List" placeholder="add">
<input type="submit" id="subButton" onclick="action()">
<!-- <button type="button" id='resetBut' onclick="deleteIl()">Reset</button>-->
<div>
<ul id="myUl" ></ul>
the js
function action() {
let item = document.createElement('li');
let inputValue = document.getElementById('tasks').value;
var t = document.createTextNode(inputValue);
item.appendChild(t);
if (inputValue === '') {
alert("you must write something!");
} else {
document.getElementById('myUl').appendChild(item);
}
document.getElementById('tasks').value = '';
const tasksDelete = document.createElement("button");
tasksDelete.classList.add("delete");
tasksDelete.innerHTML = 'X';
item.appendChild(tasksDelete);
document.getElementsByClassName("delete").onclick = log();
//document.getElementsByClassName("delete").addEventListener("click", log());
function log() {
console.log("name")
}
//tasksDelete.document.getElementById('myUl');
//tasksDelete.removeChild();
}
i'm trying to put a delete button on the elements 'li' (this works), and trying to use the removeChild() but i'm getting 'Uncaught ReferenceError: removeChild is not defined', so to see if it's working i've change the removeChild() for the log function, and now the log function appears in the console when a press the subButton and not when i click on the delete button.

JS - QuerySelector null on element that does exist [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
I've searched for about a good 1 hour and found nothing. I've attempted the 'fixes' I've come across and they do not work on my code. Albeit that the code provided works on its own file, it does not work within mine.
Html:
<div class="result">Pizza</div>
<div class="choices">
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissors</button>
</div>
</body>
</html>
JS:
let buttons = document.getElementById("#rock").addEventListener("click");
let rock = document.querySelector('#rock');
//check if id exists
let str,
element = document.getElementById('.choices #rock');
if(element != null){
str = elemen.value;
console.log(str);
}else{
str = null;
console.log(str);
}
if it need be, I'll post my entire code. Hopefully, this is enough to replicate the error on your end.
Thanks in advance!
getElementById takes only an id as argument, not a query.
Either use
element = document.querySelector('.choices #rock');
or
element = document.getElementById('rock');
The second form is much cleaner as only one element can have a given id. Keep composite query finished by an id to the very rare cases you want to apply it to the case the element may be or not be inside an another one.
You have some typos, but you are also missing a load or DOMContentLoaded listener. You are likely querying for the element before it exists on the page:
document.addEventListener('DOMContentLoaded', function() {
var rock = document.querySelector('#rock');
var str;
if (rock) {
str = rock.value;
console.log(str);
} else {
str = null;
console.log(str);
}
});
<div class="choices">
<button id="rock" value="rock">Rock</button>
<button id="paper" value="paper">Paper</button>
<button id="scissors" value="scissors">Scissors</button>
</div>
I don't understand the logic of your code, but you need to change the way you're getting the elements.
You're trying to get element by id, however, what you really want is get the element using querySelector.
Check on the changes I did on your code.
let buttons = document.getElementById("rock").addEventListener("click", function() {});
let rock = document.querySelector('#rock');
//check if id exists
let str;
let element = document.querySelector('.choices #rock');
if (element != null) {
str = element.value;
console.log(str);
} else {
str = null;
console.log(str);
}
<div class="choices">
<button id="rock" value="rock">Rock</button>
<button id="paper" value="paper">Paper</button>
<button id="scissors" value="scissors">Scissors</button>
</div>

Get the last occurrence of an element [duplicate]

This question already has answers here:
Get multiple elements by Id
(14 answers)
Closed 5 years ago.
getElementById(id) returns the element with the matching ID attribute. How can I get the last occurrence of this element, as opposed to the first?
<!DOCTYPE html>
<html>
<body>
<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
alert(document.getElementById("username").innerHTML);
}
</script>
</body>
</html>
id is always unique. No two DOM elements can have the same id. In your case use the class attribute. Use getElementsByClassName which will return a collection. Get its length and use that value to get the last element.
function getLast() {
var getLastElemIndex = document.getElementsByClassName("username").length - 1;
console.log(getLastElemIndex)
alert(document.getElementsByClassName("username")[getLastElemIndex].innerHTML);
}
<div class="username">Lisa</div>
<div class="username">Chris</div>
<button onclick="getLast()">Click me</button>
id should be unique. But we don't have control on how people write their code and I also meet this case sometimes: "I need to parse the page and they are using same id"
You can treat id as an attribute and use querySelectorAll:
<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
tags = document.querySelectorAll('[id="username"]');
alert(tags[tags.length - 1].innerHTML);
}
</script>
And the best practice should be using class.
The id of a HTML element is meant to be unique. You should specify the class instead:
<div class="username">Lisa</div>
<div class="username">Chris</div>
Then use Document.getElementsByClassName() to get all elements of that class:
var usernames = document.getElementsByClassName("username");
Alternatively, you can use Document.querySelectorAll():
var usernames = document.querySelectorAll(".username");
And then you can get the last one:
var lastUsername = usernames[usernames.length - 1];
Even you can do it by tag name div, as #brk said id must be unique.
function getLast(){
var divs = document.querySelectorAll("div");
console.log(divs[divs.length - 1].textContent);
}
getLast();
<button onclick="getLast()">Click me</button>
<div>Lisa</div>
<div>Chris</div>

Why is my clear function not working? [duplicate]

This question already has answers here:
Is "clear" a reserved word in Javascript?
(4 answers)
Closed 6 years ago.
function clear() {
document.getElementById("1").innerHTML = '';
document.getElementById("2").innerHTML = '';
document.getElementById("3").innerHTML = '';
}
<button onclick="clear()">Clear</button>
That is the function and my button that runs it.
The purpose of the function is to clear the paragraphs, but the button does nothing when I tested it out.
Why is this function not running when the button is clicked?
EDIT: sorry if the answer is obvious, i'm a beginner to JS
EDIT: HTML:
<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
There is also a JS function that changes the text of the Paragraphs, but it doesn't loop
Don't name the function clear as the DOM has an old global method named clear. Try something else like clearMe
function clearMe() {
document.getElementById("1").innerHTML = '';
document.getElementById("2").innerHTML = '';
document.getElementById("3").innerHTML = '';
}
<div id="1">
foo
</div>
<div id="2">
foo
</div>
<div id="3">
foo
</div>
<button onclick="clearMe()">Clear</button>

Autocomplete jQuery plugin not working, claiming a variable is undefined [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jQuery variable claiming it's undefined when it has been defined
The problem is that when opening it in firefox and typing a value for input 1 and selecting it, firebug says that the variable phone isn't defined. I tried defining the variables at the start but it still ceased to work.
This is the jQuery:
$(document).ready(function() {
var phone; //fix scoping
var phoneid;
var firmware;
var firmwareid;
$("#input1").autocompleteArray(["iPhone 2G","iPhone 3G","iPhone 3GS","iPhone 4","iPhone 4s"],
{ minChars:1,
matchSubset:1,
onItemSelect:selectPhone,
onFindValue:findPhone,
autoFill:true,
maxItemsToShow:10,
selectFirst:true,
});
$("#input2").autocompleteArray(["1.1","1.2","1.3","1.4","1.5"],
{ minChars:1,
matchSubset:1,
onItemSelect:selectFirmware,
onFindValue:findFirmware,
autoFill:true,
maxItemsToShow:10,
selectFirst:true,
});
function findPhone(li) {
if( li == null ) return alert("No match!");
phone = li.selectPhone;
phoneid = phone.replace("iPhone ","iphone").toLowerCase();
};
function findFirmware(li) {
if( li == null ) return alert("No match!");
firmware = li.selectFirmware;
firmwareid = phone.replace(".","");
$(".info").hide
$(phoneid+firmware).show
};
function selectPhone(li) {
findPhone(li);
}
function selectFirmware(li) {
findFirmware(li);
}
});
And this is the HTML:
<div id="formcontainer">
<input id="input1"/>
<input id="input2"/>
</div>
<div id="iphone2g11" class="info" style="display:none">iPhone 2G</div>
<div id="iphone2g12" class="info" style="display:none">iPhone 3G</div>
<div id="iphone2g13" class="info" style="display:none">iPhone 3GS</div>
<div id="iphone2g14" class="info" style="display:none">iPhone 4</div>
<div id="iphone2g15" class="info" style="display:none">iPhone 4S</div>
I'm using this plugin for autocomplete http://www.pengoworks.com/workshop/jquery/autocomplete.htm
The problem is in your findFirmware() function, change it to
function findFirmware(li) {
if( li == null ) return alert("No match!");
firmware = li.selectFirmware;
firmwareid = phone.replace(".","");
$(".info").hide();
$('#' + phoneid + firmwareid).show(); // This line was messed up
};
There two problems with this line $(phoneid+firmware).show, well four if you count the missing parenthesis and semicolon but...
The div your trying to show has an ID, you don't have # in your selector to select the element by ID
firmware contains the unparsed string with the period so phoneid + firmware becomes iphone2g1.2 when your div ID is iphone2g12 thus you needed to use firmwareid in which you parsed it out of.
Fiddle Demo: http://jsfiddle.net/AaNWM/
Its undefined because you do:
li.selectPhone;
Which .selectPhone doesn't exist on the li element passed in. So, once you get to replacing the string, you get an error.
Assuming that I may, possibly, think, that I might know what you are trying to do, I changed li.selectPhone and li.selectFirmware to li.innerHTML and it works fine. jsFiddle.
Edit: You also were using phone.replace in your firmware function so I changed that as well in the above fiddle.
phone is undefined because li.selectPhone is undefined.
It's hard to guess why that's missing without seeing autoCompleteArray(), which doesn't seem to be part of the jQuery autocomplete plugin, at first glance?

Categories

Resources