How to remove a div in a site using a Chrome extension? - javascript

There's this div in a site:
<div class="section1">
....
</div>
I want to remove it using a Chrome extension... Can someone give only the javascript code alone? Thanks.

function removeElementsByClassName(names) {
var els = document.getElementsByClassName(names),
i, element;
for (i = els.count - 1; i > 0; i -= 1) {
element = els[i];
element.parentElement.removeChild(element);
}
}
removeElementsByClassName('section1');

function removeElement(parentDiv, childDiv){
if (childDiv == parentDiv) {
alert("The parent div cannot be removed.");
}
else if (document.getElementById(childDiv)) {
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
}
else {
alert("Child div has already been removed or does not exist.");
return false;
}
}
removeElement('parent','child');

If by removing you simply mean hiding then you can run this from a content script:
document.querySelector('div.section1').style.display = 'none';
(this assumes there is only 1 section1 element on the page, otherwise you would need to use document.querySelectorAll and filter the results based on some criteria)

Related

if else statement javascript to make div change color based on .scrollTop

I am a beginner coder and I'm trying to change the background color of a div based on how far down scrolled the webpage is, where am I going wrong?
Do I need to put in something to call the scrollTop amount?
(function () {
var scroll = .scrollTop;
if (scroll > 50) {
document.getElementByClassName("shop").style.backgroundColor = '#99C262';
}
else
{
document.getElementByClassName("shop").style.backgroundColor = ‘red’;
}
})();
Lose the dot, instead of “.shop” go for “shop”
And the actual function getElementsByClassName and it returns a collections of divs with the class name. But you need the first one (assuming you have only one such div) hence the 0 index in array
parentDOM.getElementsByClassName('test')[0].style.backgroundColor = "red";
<p class="test">hello here</p>
Many errors in the code....
var scrole = .scrollTop; not sure if you are trying to assign any value or is it window.scrollTop.
document.getElementByClassName(".shop") should be changed to document.getElementByClassName("shop")
else if (scroll < 50 ){ //statement } to be changed to else { //statement }
function is wrapped in small bracket but has never been invoked.
Self invoking function example :-
(function(){
console.log(Math.PI);
})();
Using a dot before a class name when getting it in javascript using getElementsByClassName is an Incorrect Syntax. Below is the correct syntax.
document.getElementsByClassName("shop")
Tip: Always Use the console window to monitor your Syntax and other errors.
Your code are only executed once if you don't attach a listener. Let me just use these code from MDN docs with a bit of edit. The docs
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
if (scroll_pos > 50) {
document.querySelector(“.shop”).style.backgroundColor = '#99C262';
} else if (scroll_post < 50) {
document.querySelecttor(“.shop”).style.backgroundColor = ‘red’;
} else {
// add more colorrrs!
}
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});

Creating a form page with java

Noob here again. I have a div id setup and the following code works for the one instance, but I need to have when they click static 3 forms areas aren't hidden any more. I know its a for loop, but I can't get they syntax right.
<script type="text/javascript">
function Protocols(val){
var element=document.getElementById('static_ip')
if(val=='pick a protocol'||val !='Static')
element.style.display='none';
else
element.style.display='block';
}
</script>
Here's an example, using querySelectorAll:
function Protocols(val){
const hideOrShow = document.querySelectorAll('#static_ip, #id2, #id3')
for (element of hideOrShow) {
if (val !== 'Static') {
element.style.display = 'none';
} else {
// resetting to empty string falls back to default value
element.style.display = '';
}
}
}
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
Got it, Its working now. Thanks for the help.
<script type="text/javascript">
function Protocols(val){
var element=document.querySelectorAll('#static_ip')
for ( i=0; i < element.length; i++) {
if(val=='pick a protocol'||val !='Static'){
element[i].style.display='none';
} else {
element[i].style.display='block';
}
}
}
</script>

How to find if parent Node has no Children

I'm not sure if I am using the correct syntax, as my ELSEIF doesn't appear to be firing. Is this the correct syntax, or what is the best way to test it?
<script>
function OnLoad() {
var links = document.getElementById("<%=TreeView1.ClientID %>").getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].setAttribute("href", "javascript:NodeClick(\"" + links[i].id + "\", \"" + links[i].getAttribute("href") + "\")");
}
}
window.onload = OnLoad;
function NodeClick(id, attribute) {
var nodeLink = document.getElementById(id);
if (nodeLink.hasChildNodes)
{
eval(attribute);
}
else if (nodeLink.hasChildNodes == false)
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
}
</script>
If I move the alert/open window by itself it works, so I feel that the problem lies in this line:
else if (nodeLink.hasChildNodes == false)
The syntax for hasChildNodes says it is a method .i reckon changing it to a method should solve the problem
It should be noted, hasChiildNodes() considers whitespace and comments. From the MDN docs
childNodes also includes e.g. text nodes and comments. To skip them, use ParentNode.children instead.
i.e
if (nodeLink.hasChildNodes())
{
eval(attribute);
}
else if (!nodeLink.hasChildNodes())
{
alert(nodeLink.innerHTML + " clicked");
window.open("../NewFolder/addNewProduct.aspx");
}
else
{
return;
}
Check the two fiddles to get the difference
hasChildNodes fiddle .
ParentNode.Children fiddle
parentNode.children.length;
if it is 0, then no child node at all
For example
console.log(document.getElementById('d1').children.length); //->0
console.log(document.getElementById('d2').children.length); //->3
<div id="d1"></div>
<div id="d2">
<div></div>
<div></div>
<div></div>
</div>

How to detect click outside an element with a class selector Using Pure Javascript (without using Jquery)

I want to detect clicking outside an element using class name as
selector
<div id="popOne" class="pop">...</div>
<div id="popTwo" class="pop">...</div>
...
<div id="popLast" class="pop">...</div>
<script>
var popElement = document.getElementById("pop");
document.addEventListener('click', function(event) {
var isClickInside = popElement.contains(event.target);
if (!isClickInside) {
alert("Outside");
//the click was outside the popElement, do something
}
});
</script>
As an alternative to iterating over all possible .pop elements for every click event, just traverse the DOM looking to see if the node or any ancestor thereof has the desired class:
document.addEventListener('click', function(e) {
var node = e.target;
var inside = false;
while (node) {
if (node.classList.contains('pop')) {
inside = true;
break;
}
node = node.parentElement;
}
if (!inside) {
alert('outside');
// click was outside
} else {
alert('inside');
}
});
This would make the performance scale relative to the depth of the DOM tree, rather than by the number of .pop elements.
Made the following changes to the script
var popElement = document.getElementsByClassName("pop");
document.addEventListener('click', function(event) {
for(i=0; i < popElement.length; i++){
popEl = popElement[i];
var isClickInside = popEl.contains(event.target);
if (!isClickInside) {
alert("Outside");
} else {
alert("Inside");
break;
}
}
});
First of all you are using the incorrect function to get Element. It should be getElementsByClassName("pop") and not getElementsById("pop") and also getElementsByClassName returns a HTMLCollection of elements having that class. So you need to loop over them and check whether clicked inside any of them or not. Here is the demo. Have added some style to divs so that it easy to differentiate between them. And also if need to check whether the click was on any of the divs then you need to check for that and as soon as you find that it was clicked inside a div having class pop. Break from the loop and continue with you conditions. But if for all the elements the IsClickedInside comes out to be false then you can handle it accordingly
document.addEventListener('click', function(event) {
var popElement = document.getElementsByClassName("pop");
var isClickInside;
for (var i = 0; i < popElement.length; i++) {
isClickInside = popElement[i].contains(event.target);
if (isClickInside) {
break;
//alert("Outside of" + popElement[i].id);
//the click was outside the popElement, do something
}
}
if(isClickInside){
alert("Clicked inside one of the divs.");
}else{
alert("Clicked outside of the divs.");
}
});
div {
height: 100px;
border:2px solid black;
}
<div id="popOne" class="pop">...</div>
<div id="popTwo" class="pop">...</div>
...
<div id="popLast" class="pop">...</div>
Hope it helps :)

make an anchor toggle function which appends data to textarea on click and removes on reclick

i m trying to make an anchor toggle function which appends data to textarea on click and removes on reclick. here is the jsfiddle.
`
function btnsInit()
{
var i, a = document.getElementById('btns').getElementsByTagName('a');
for (i = 0; i < a.length; ++i)
{
var str=document.getElementById('ta').value;
var index= str.indexOf(a[i]);
if(index!=-1)
{
a[i].onclick = btnClick;
}
else
{
str.replace(a[i],"_");
}
}
}
function btnClick(e)
{
document.getElementById('ta').value += this.firstChild.nodeValue + ',';
xPreventDefault(e);
return false;
}
`Please reply ASAP
Here is new js code, you can use it -
<div id='btns'>
<p>
<!-- adding id to element, helps to maintain the list
of element which have been clicked, and also helps in
distinguishing between two elements have same text.
Dont forget to add href="#' or href="javascript:void(0)"
else your page may refresh and form data will be lost -->
<a id="a1" href='#'>category</a>
</p>
<p>
<a id="a2" href='#'>url</a>
</p>
</div>
<textarea id='ta' rows='10' cols='20'></textarea></body>
Javascript -
window.onload = btnsInit;
var selected = {};//keeps list of selected links
function btnsInit() {
var i, a = document.getElementById('btns').getElementsByTagName('a');
for (i = 0; i < a.length; ++i) {
a[i].onclick = btnClick;
}
}
function btnClick(e) {
if (selected[this.id]) {
delete selected[this.id];//deleting if already been clicked
} else {
selected[this.id] = this.innerHTML;//adding to the selected list
}
updateTextArea();
xPreventDefault(e);
return false;
}
function updateTextArea() {
var ta = document.getElementById('ta');
var val = "";
for ( var id in selected) {
val += selected[id] + ",";
}
ta.value = val;//updating from selected list
}
function xPreventDefault(e) {
if (e && e.preventDefault)
e.preventDefault();
else if (window.event)
window.event.returnValue = false;
}
Problems with your code -
btnsInit was not actually assigning onclick listeners to <a> elements.
Re click on a link was not handled or not handled properly(if handled).
Use attribute/value href=' ' for a tag which is refreshing the page.
Update - questions asked in comments
Was my code not working as it was refreshing the page?
No, It was not. It was missing reclick handling and btnsInit was not working properly.
Is delete a predefined function?
delete is a JavaScript keyword, which delete an object property.
About delete keyword
What is the use of 'this'?
this is another keyword which holds the reference of the object in context, in this case it holds the element clicked.
More about this keyword

Categories

Resources