jQuery addclass to each Wordpress post image - javascript

this is what I have so far:
<script>
$(document).ready(function(){
$(".entry-content img:first").addClass('postimage');
});
</script>
As you can see, for the first image of .entry-content it adds my class. Cool, that works fine. Uncool, it doesn't work for every post but only the first on the page.
I'm not sure how to fix this. Do I need to use .each in some way or is there something wrong with what I have already?
Thanks

This is because the CSS selector is selecting the first .entry-content img, not the first img in every .entry-content. It's about operator precedence.
You can iterate through each .entry-content and select the img:first in that node manually, though.
$(document).ready(function(){
var entries = document.querySelectorAll('.entry-content');
for (var i = 0; i < entries.length; i++) {
var firstImage = $(entries[i].querySelectorAll('img:first')[0]);
firstImage.addClass('postImage');
}
});

this will iterate over all your posts and apply the class to the first image within each.
$.each('.entry-content', function() {
$(this).find('img:first').addClass('postImage');
});

A variation of Paul Dragoonis' answer:
$(".entry-content").each(function ()
{
$("img:first", this).addClass("postImage");
});

Related

Get all the paragraph of a class

I am trying to echo all the paragraphs of a specific class. The source code has this structure:
<div class='example'>
<p> this is the first paragraph </p>
<p> this is the second paragraph </p>
</div>
I have tried different ways (getElementsByTagName and stuff like this but they didn't work). Could you suggest me something?
Simply get the value by classname.
Use Js Function getElementsByClassName
Try below code for Javascript :
var x = document.getElementsByClassName("example").innerHtml;
console.log(x);
alert(x);
Also working jsfiddle with javascript - https://jsfiddle.net/ayh0gk7s/1/
If you are prefer to use jQuery then try below code :
$('.example p')
jsfiddle link for jquery - https://jsfiddle.net/3nhb1agu/
Fetch them via XPath:
$doc = new DOMDocument;
$doc->load('file.html');
$xp = new DOMXPath($doc);
$pars = $xp->query('//div[contains(#class, "example")]/p');
// For exactly one class:
//$pars = $xp->query('//div[#class = "example"]/p');
foreach ($pars as $p) {
var_dump($p->nodeValue);
}
The code fetches text representations of the paragraph nodes.
In JQuery, you can print the parent children element. Try this !
$(document).ready(function(){
$("div.example").children("p").each(function(){
alert($(this).text());
console.log($(this).text());
});
});
Using jQuery:
$('.example p')
This should hopefully get you the desired paragraphs.
You can use querySelectorAll.
var myParagraphs = document.querySelectorAll('.example p');
for (var i = 0 ; i < myParagraphs.length ; i++) {
console.log(myParagraphs[i]);
}

Changing table cell colors in Javascript without the use of id's

I'm working on a small project where I'd like to change the background color of a table's cells while the mouse hovers over each cell. I'm able to do it with an individual cell with document.getElementById("cell1"); etc. but haven't found a way to make life easier by selecting all of the td tags and avoiding giving each cell its own id. I've tried document.getElementsByTagName but the console returns that cell.addEventListener is not a function. I must be using the selectors wrong or am not understanding the correct usage of event handling. I've found a similar question on here but it doesn't address using solely javascript which i'd like to do.
var cell = document.getElementsByTagName("td");
cell.addEventListener("mouseover", function() {
this.style.backgroundColor="red";
cell.addEventListener("mouseout", function() {
this.style.backgroundColor="";
})
});
Why not CSS? The :hover pseudo class is much easier and conserves code length and complexity, and is ultimately faster.
td:hover{ /* insert proper selector here */
background-color:red;
}
You should be iterating the set. "The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name." - https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
for(var i = 0; i < cell.length; i++){
cell[i].addEventListener("mouseover", function() {
this.style.backgroundColor="red";
};
cell[i].addEventListener("mouseout", function() {
this.style.backgroundColor="";
});
}
However, a better way to do this would be a simple hover rule in css
td:hover{
background-color: red;
}
Here is a jQuery solution
$(document).ready(function() {
$("td").on("mouseover mouseout", function() {
$(this).toggleClass("red");
});
});
http://jsfiddle.net/kwagtd0d/1
You can add and remove classes with jQuery by listening for events, but it's easiest to do this with css.
td:hover
JavaScript solution
var cells = document.getElementsByTagName("td");
This returns a collection of td elements. We can now iterate through this selection.
for(var i = 0; i < cells.length; i++){
cells[i].addEventListener("mouseover", function() {
this.classList.add("red");
};
cells[i].addEventListener("mouseout", function() {
this.classList.remove("red");
});
}
http://jsfiddle.net/qknjyaaw/

msDropDown Delete all options

Please let me know how can I remove/clear all options from msDropDown. I have tried the below code and its not working fine.
oHandler2 = $("#main").msDropDown().data("dd");
oHandler2.remove();
Thanks in Advance.
Lampy
You need to specify an index when calling the .remove() method and you can get the count of all options by accessing the childElementCount property. Then you just need to remove all the options. Example below:
var oHandler2 = $("#main").msDropDown().data("dd");
for(var i = 0; i < oHandler2.childElementCount; i++){
oHandler2.remove(0); //remove the current first option
}
In my opinion the best way to delete all item is
var oHandler = $("#main").msDropDown().data("dd");
oHandler.set("length", 0);
If you dont need to remove specify item, you can delete your element. And then create new one.
HTML
<div class="mainSection">
<div id="main"></div>
</div>
Script
<script>
$("#main").remove();
$(".mainSection").append("<div id='main'></div>");
$("#main").msDropDown().data("dd");
</script>

getElementById with changing IDs

I need to hide all the elements that have the string "replies-36965584" anywhere in their IDs.
HTML:
<div id="replies-36965584_1">aaaa</div>
<div id="replies-36965584_2">aaaa</div>
<div id="replies-36965584_3">aaaa</div>
<div id="replies-36965584_4">aaaa</div>
<div id="replies-36222224_2">nnnn</div>
JavaScript:
document.getElementById("replies-36965584").style.display="none"
How can I modify this JS to select the first four elements?
You can do this with CSS and attribute selectors.
[att^=val]
Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.
Source: http://www.w3.org/TR/css3-selectors/#attribute-substrings
jsfiddle
CSS
[id^="replies-36965584_"] {
display: none;
}
Is using jQuery an option? If so, this is dead simple:
$(document).ready(function(){
$('div[id^="replies-36965584"]').hide();
});
If you're unfamiliar with jQuery, here's a link to get started: http://learn.jquery.com/javascript-101/getting-started/
EDIT: Fixed syntax error.
EDIT: Added jsFiddle: http://jsfiddle.net/xbVp9/
If you don't know certain literal values but you know the general pattern and only the number will change, then I will consider some matching with regular expresiion.
You can do it the painful way:
var o = document.getElementsByTagName("div");
for (var i=0;i<o.length;i++) {
if(o[i].id.indexOf('replies-36965584') == 0) {
o[i].style.display = 'none';
}
}
The only way to do this with vanilla javascript that I know of, is to fetch all the divs on the page, and test the id's for the ones you want.
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; ++i) {
var div = divs[i];
if (/replies-36965584/.test(div.id)) {
div.style.display = 'none';
}
}

Get Inner HTML of Multiple Elements

I want to get the content of multiple Spans. Here is my code:
http://jsfiddle.net/4XumV/
It's supposed to give me "111, 222, 333, 444". It gives me "undefined" instead.
What's wrong with my code?
Well, you weren't actually getting the innerHTML property, you were getting an undefined html property. Change it to innerHTML and it will work.
http://jsfiddle.net/4XumV/1/
This should work:
$(function()
{
var allLatestNews = $("#main").find('span');
$.each(allLatestNews, function(i,val){
alert($(val).text());
});
});
I was wondering WHY your code wasn't working and JQuery does return an array of elements from the selector, this could have also worked:
for(var i = 0; i < allLatestNews.length; i++)
{
alert($(allLatestNews[i]).text());
}
First wrap the element as a JQuery object and then querying text() not html, which is accessed by a function not a property.
Your updated fiddle: http://jsfiddle.net/4XumV/9/
You seem to be confusing jquery's html with innerHTML.
You can either use innerHTML:
http://jsfiddle.net/4XumV/3/
alert(allLatestNews[i].innerHTML);
or jquery's html:
http://jsfiddle.net/4XumV/5/
alert(allLatestNews.eq(i).html());
Try this it should work
allLatestNews.each(function()
{
alert($(this).html());
});
var $elms = $('#main').find('span');
$elms.each(function(){ alert($(this).text()); });
http://jsfiddle.net/4XumV/2/
This is working
var allLatestNews = $("#main").find('span');
$.each(allLatestNews ,function( index , value){
console.log($(value).html());
});
instead of console.log($(value).html()); you can write alert($(value).html());
The property of a DOM element to return the inner HTML is named innerHTML not html
allLatestNews[i].innerHTML
Or using jQuery
$(allLatestNews[i]).html()
Updated JS Fiddle
you can also use this
var allLatestNews = $(this).find("#main span");
for(var i = 0; i < allLatestNews.length; i++)
{
alert(allLatestNews[i].innerHTML);
}

Categories