Get CSS position property of element with JavaScript - javascript

For example I have this <div> with the following CSS:
.some-div{
position: relative;
top: 50px;
}
<div class="some-div">
<p>Some content</p>
</div>
How do I get the CSS property position of the element with JavaScript (which in this example should result in the string "relative")?

Window.getComputedStyle()
The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain
const element = document.getElementById('your_element_id');
const computedStyles = getComputedStyle(element);
const position = computedStyles.position;

Assuming your "class" has only one element:
HTML
<div class="some-div"">
<p>Some text</p>
</div>
JAVASCRIPT
let someDiv = document.getElementsByClassName('some-div')[0];
someDiv.addEventListener('click', () => {
console.log(this.getComputedStyle(someDiv).getPropertyValue('position'));
});

var element = document.querySelector('.some-div');
var style = window.getComputedStyle(element);
var pos = style.position;
console.log(pos);
Try this.
The Console output must be: "relative"

Related

How to access a <p> inside three layers of <div> using Javascript?

I'm trying to use Javascript so that a paragraph will alternate between two texts when the user presses a button on the webpage. The problem is that the <p> element I'm trying to manipulate lies within a <div> within a <div> within a <div>.
A low-level mockup of my code can be seen below:
<div id="div1">
<div id="div2">
<div id="div3">
<p>text1</p>
</div>
</div>
</div>
All solutions I've found only state what to do if the <p> is within one <div>; solutions which have not worked for me.
Here's my latest attempt:
function translate() {
var x = document.getElementById("div1").getElementById("div2").getElementById("div3").getElementsByTagName('p')[0];
if (x.innerHTML === "text1") {
x.innerHTML = "text2";
} else {
x.innerHTML = "text1";
}
}
How would I get this to work?
Edit: Nothing seems to be working so far. The <div> element all have classes, but that shouldn't affect things, right?
Edit2: My apologies for taking up your time, but I've found the issue was something else entirely. I'd been using a reserved word for my function call this whole time and had somehow never noticed that that was the issue instead. Thanks again to those who answered, and I shall look deeper at my code before posting my next question.
Why not just use
var x = document.getElementById("div3")
If accessing by the Id directly, it does not really matter what the other DIVs are.
If divs are always in that order, you can do it like this:
var x = document.querySelector('#div1 #div2 #div3 p');
You can use document.querySelectorAll to get an array of all p tags on the page.
const pTags = document.querySelectorAll('p')
pTags.forEach((p, i) => {
if(i % 2 === 0) {
p.innerHTML = 'text1'
} else {
p.innerHTML = 'text2'
}
})
Instead of Ids, you can be more specific & try the following:
var x = document.querySelector('div > div > div > p')
This will be a very strict implementation & follows the condition without the ids or classes.
Use querySelector in order to use the CSS selector #div3 p which means "pick up the paragraph element that is inside the element that has a div3 id".
Then, as you're just changing a string of text, change either the textContent of that element, or its innerText (there are subtle differences between them.)
const para = document.querySelector('#div3 p');
const button = document.querySelector('button');
button.addEventListener('click', translate);
function translate() {
if (para.textContent === 'text1') {
para.textContent = 'text2';
} else {
para.textContent = 'text1';
}
}
<div id="div1">
<div id="div2">
<div id="div3">
<p>text1</p>
</div>
</div>
</div>
<button type="button">Translate</button>

Count psuedo elements (`::before` & `::after`) on page with VanillaJS [duplicate]

I have this simple html code. I need to be able to determine if the ::before is being applied to .icon-player-flash
<div id="TestSwitch">
<i class="icon-player-html5"></i>
<i class="icon-player-none"></i>
<i class="icon-player-flash"></i>
</div>
I thought this would work but it's always returning 0 for the length.
var flashplayer = $(".icon-player-flash:before");
console.log("count: " + flashplayer.length);
What am I missing?
Use getComputedStyle and check the value of content. If it's none then the pseudo element isn't defined:
var elem = document.querySelector(".box");
var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
console.log(c);
var elem = document.querySelector(".alt");
var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
console.log(c);
.box:before {
content:"I am defined"
}
<div class="box"></div>
<div class="alt"></div>
This property is used with the :before and :after pseudo-elements to generate content in a document. Values have the following meanings:
none
The pseudo-element is not generated. ref
If you want to count simply consider a filter:
const elems = document.querySelectorAll('div');
const divs = [...elems].filter(e => {
var c = window.getComputedStyle(e,"before").getPropertyValue("content");
return c != "none"
});
console.log(divs.length)
.box:before {
content:"I am defined"
}
<div class="box"></div>
<div class="box alt"></div>
<div class="alt"></div>
<div ></div>

set value of element

I want to create a new element and then set the value of the new element. Then add the element to div.
var x = document.getElementById("Header");
var element =document.createElement("test");
var addel=x.appendChild(element)
<div id="Header">
<h1>
<img height="150" src="http://test.com/im.jpeg">
<span>test</span>
</h1>
</div>
for instance, create a new element called "test" then add the element to div and set the value of test="1".
Your new element won't be recognised by the browser as html has fixed set of elements
You perhaps need to use a text based element like span,p or you can simply set innerText of a block element like div to "1"
If you want to create your own elements You can refer here
https://developers.google.com/web/fundamentals/web-components/customelements
You can also extend existing elements to form new elements
You can use Node.textContent or HTMLElement.innerText property to set the text:
var x = document.getElementById("Header");
var element =document.createElement("test");
element.textContent = "1";
var addel=x.appendChild(element);
<div id="Header">
<h1>
<img height="150" src="http://test.com/im.jpeg">
<span>test</span>
</h1>
</div>
change the code with
var x = document.getElementById("Header");
var element =document.createElement("test");
element.setAttribute('value','1');
var addel=x.appendChild(element);

Get value from data-section based on element ID

I'd like to render the section id="zero" data-section value in the h2 in my footer section dynamically. Since all of my pages will have different data-section values, I'm hoping we can target the section id="zero". This way I can use only one footer across my site. I am just not versed in javascript or jQuery to properly assign and call. I know there is document.getElementById('zero') but then getting the value from data-section and having it appear within my H2 I am not clear on.
<section id="zero" class="section-wrap" data-section="Page Name"></section>
<section id="footer">
<h2></h2>
</section>
Here's some Javascript that should help.
//Get the data-section value
let val = document.getElementById('zero').dataset.section;
//find the first h2 inside footer section
let header = document.getElementById('footer').getElementsByTagName("h2")[0];
//set the value
header.textContent = val;
Vanilla JS way
function start(){
// Find element with id="zero"
const section = document.querySelector('#zero');
// Find the h2 element nested inside an element with id="footer"
const footer = document.querySelector('#footer h2');
// Get value of data-section attribute
const dataSectionValue = section.getAttribute('data-section');
// Set value in your h2 tag
footer.innerText = dataSectionValue;
}
window.onload = start;
jQuery way
$(document).ready(function(){
const section = $('#zero');
$('#footer h2').text(section.data('section'));
});

How to dynamically change html elements and copy attributes with javascript

How can you change the hyrarchy / structure of html when it's rendered with javascript?
I would like to remove a parent div and copy it's attribute and classname
to it's child element. But I want to do this in the whole page that contains a certain class name.
In code example: I need this code
<div class="abc" myid="123" position="2">
<div class="someblock">
<p>Some paragraph</p>
<img width="140px; height: 140px; class="myimg" src="url to imgage">
</div>
changed to :
<div class="someblock" class="abc" myid="123" position="2">
<p>Some paragraph</p>
<img width="140px; height: 140px; class="myimg" src="url to imgage" />
</div>
Does anyone know how this can be done with JavaScript, or jQuery?
Thanks in advance!,
Chris.
You can try:
<script>
$('.abc').each(function(){
$(this).children().addClass($(this).attr('class'));
$(this).children().attr('myid', $(this).attr('myid'));
$(this).children().attr('position', $(this).attr('position'));
$('body').append($(this).html());
$(this).remove();
});
</script>
Be careful.
$('.someblock').each(function () {
var pt = $(this).parent(),
cl = pt.attr('class'),
id = pt.attr('id'),
pos = pt.attr('position');
$(this).unwrap().attr({id:id, position:pos}).addClass(cl);
});
May be something like this could help:
function deleteParent(id){
var element = document.getElementById(id);
var parent = element.parentNode;
var grandParent = parent.parentNode;
var html = parent.innerHTML;
grandParent.removeChild(parent);
grandParent.innerHTML += html;
}
$('.abc .someblock').contents().unwrap().parent().addClass('someblock');
Demo ---> http://jsfiddle.net/VQRQV/1/
var el = document.getElementById('123');
if(el) {
el.className += el.className ? ' someblock' : 'abc';
}
You can do this first by getting all the elements as
var allElem = document.getElementByID ("*");
then loop through all the elements.
To get to child element check whether a element has children find the last child and a get attribute value example:
var elemVal = allElem[i].className ; or allElem[i].getAttribute("xyx")
and then put the value of this element to desired element in html.
document.getElementById("div").className = elemVal ;

Categories

Resources