I want to use Javascript or jQuery to get the first <ul> element the post body and display it. On Blogger, the tag <data:post.body/> displays the whole post.
<div class="post-cover">
<img src="BIG-IMAGE"/>
</div>
<ul>
<li>CONTENT 1</li>
<li>CONTENT 2</li>
<li>CONTENT 3</li>
<li>CONTENT 4</li>
</ul>
The reason is: I need these ul elements to display in the homepage, but I cannot load the original image because they are all large and would affect the loading time dramatically.
I also cannot use display: none for the image because it loads the same way. I'm using Blogger.
I think it is similar when getting a thumbnail (first src) or the first string (for summaries) but I don't know how to make it.
UPDATE
ul:first gets the first ul element on the page.
$("ul:first").css(//whatever you want to do);
You can use $("ul:first") to get the ul and use any jquery function to work with that element.
to get the first element of a div
In your case, that's an img but not a ul tag.
If you really want to get the first element whatever it is, you can do it this way:
$(".post-cover").children().first().css({ // ... });
jQuery children() takes all children in DOM
jQuery first() takes the first one of them
However, if you know which element you are going to take, it is better to give him a name and access it using a name:
// HTML
<div class="post-cover">
<img src="BIG-IMAGE" id="post-cover-image"/>
</div>
// JS
$("#post-cover-image").css({ // ... });
As the post title says - get the first element from a div (and display it, using jQuery):
$( ".post-cover ul" ).first().show();
Preload images, which it seems you may be trying to actually do:
$.preloadImages = function() {
for (var i = 0; i < arguments.length; i++) {
$("<img />").attr("src", arguments[i]);
}
}
$.preloadImages("BIG-IMAGE.jpg");
First you need to find the image element of the div which like this :
var div_post_cover = document.getElementsByClassName("post-cover")[0];
Note : [0] is for the first DIV that have a class of post-cover
Then you need to get the first element inside the DIV and code was like this :
var img_first = div_post_cover.children[0];
or
var img_first = div_post_cover.getElementsByTagName("img")[0];
Then you will get the value of the src
var img_first_src = img_first.src;
This will be the summarized code.
var img_src = document.getElementsByClassName("post-cover")[0].children[0].src;
You need to try this if works.
<script type="text/javascript">
window.onload = (function(){
//document.getElementsByClassName("post-cover")[0].children[0].src
alert(document.getElementsByClassName("post-cover")[0].children[0].src);
});
</script>
You can use show() and hide() :
$( ".post-cover ul:first" ).hide();
$( ".post-cover ul:first" ).show();
Related
First of all, sorry If it isn't clear in the beginning, but let me explain: I want to get the div with a class and the first <ul> from a document (I'm using blogger). I already have a JS that picks up the first image and creates a thumbnail like this:
//<![CDATA[
function bp_thumbnail_resize(image_url,post_title)
{
var show_default_thumbnail=true;
if(show_default_thumbnail == true && image_url == "") image_url= default_thumbnail;
image_tag='<img src="'+image_url.replace('/s72-c/','/')+'" class="postimg" alt="'+post_title+'"/>';
if(image_url!="") return image_tag; else return "";
}
//]]>
and below,
document.write(bp_thumbnail_resize("<data:post.thumbnailUrl/>","<data:post.title/>"));
Now the structure that I want (because I cannot display the full post in the homepage due to the size of other elements):
<div class="Title1">
<h3>Title</h3>
</div>
<ul>
<li>DESCRIPTION1</li>
<li>DESCRIPTION2</li>
</ul>
There are number of ways in which you can do that. Few are
var firstUL = document.getElementsByTagName('ul')[0];
var firstUL = document.querySelector("ul");
If you also have Jquery in use
$( "ul" ).first();
or
$("ul:first")
How to get the first element from a document in JavaScript?
You could try something as simple as:
var firstUlElement = document.getElementsByTagName('ul')[0];
The getElementsByTageName method of document
returns a live HTMLCollection of elements with the given tag name. The
subtree underneath the specified element is searched, excluding the
element itself. The returned list is live, meaning that it updates
itself with the DOM tree automatically.
as it is stated here.
var firstUl = document.querySelector('ul');
I am building a dynamic menu for a responsive page in which the left side menu hides and turns into a different menu using the slicknav solution.
Now, what I want to do is for the left menu's first link to become the title of the menu.
I can't give the tag that I need an ID because the menu is hard coded, so I need a different solution to find the inner HTML of it.
This is the HTML that I have:
<ul id="child_nav">
<li class="nav-title">My List title</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
And this is what I've been able to do with some programing to get the label of the menu to be the "My List Title" from the HTML above:
<script type="text/javascript">
$(document).ready(function(){
var E = document.getElementsByClassName('nav-title').innerHTML;
$('#child_nav').slicknav({
label: E
});
});
</script>
What am I missing?
getElementsByClassName is plural, it returns all the elements with the given class name, so it returns a NodeList not a single HTML Element.
You need to treat it like an array and either pull the first item off it or loop over it with for.
Alternatively, since you are using jQuery, just use jQuery. The html() method will give you the inner HTML of the first element in the jQuery object.
jQuery('.nav-title').html()
Since you're already using jQuery, use its selector to find the single element instead getElementsByClassName, which can return multiple elements.
$("#child_nav li.nav-title:first a").text();
Fiddle: http://jsfiddle.net/KrFs9/
try like
$(".child_nav li a:first").html()
<script type="text/javascript">
$(document).ready(function(){
var title = $('#child_nav .nav-title a:first').html();
$('#child_nav').slicknav({
label: title
});
});
</script>
This should accomplish it:
var myLabel = $('.nav-title:first').html()
I have the following code:
<div id="nav">
<ul>
<li id="tabOne" class="first current">Page One</li>
<li id="tabTwo">Page Two</li>
<li id="tabThree"><a href="./CS3.html" target="SheetView">Page Three</li>
<li id="tabFour">Page Four</li>
<li id="tabFive">Page Five</li>
<li id="tabSix">Page Six</li>
</ul>
This loads the selected page into an iframe named "SheetView." What I need to do is use JavaScript to alter the class when an option that isn't the currently selected on is clicked. I should say that I have the current class already setup in my CSS. I just have no way to trigger it.
I thought adding an onlick event to the <UL> up there and calling onclick="Javascript:changeCurrent();" but there is the problem (four actually):
Is <ul onclick="JavaScript:changeCurrent();> where I need to have the event?
What is the resulting JavaScript to make the change happen?
How can I cause the first option to be set as current by default?
Is there a way to keep the currently selected option from being an active link?
I found a few different examples but I couldn't tailor them to work for me. Any help would be most appreciated.
Since you specified that you wanted a non-jQuery response, here's a function that will toggle appropriately:
function toggleNavSelected(el){
var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
var cur = list.children[i];
if(el==cur){
cur.classList.add("current");
cur.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
return false;
});
} else {
if(cur.classList.contains("current")){
cur.classList.remove("current");
}
cur.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
});
}
}
}
Either add an onclick handler to each LI (onclick="toggleNavSelected(this);") or execute the following after the menu has loaded:
var list = document.getElementById('nav').children[0];
for(var i=0; i<list.children.length; i++){
var el = list.children[i];
el.firstChild.onclick = (function(){
toggleNavSelected(this.parentElement);
});
}
Demo: http://jsfiddle.net/bWY7P/2/
(note: The JSFiddle script has a small difference; it adds a return false; to the onclick function so that you can play with it without the links actually following the HREF attribute. Do not use that line in your live code)
Explanation:
The function looks at each LI element within the #nav element.
If that element is the element passed to the function, then it adds the class .current.
Otherwise, it removes the class .current (if present).
The second part binds a function to the onclick event of each a element that calls the toggleNavSelected() function and passes its parent element (the li) as the argument.
1) if you want to change the currently selected class when you click an item, put the onclick into the li item
2) using jquery would be very easy here, all you have to do is import the jquery file with the <script> tag and you're ready! For example, you could do onclick="changeClass(this);" on the <li> tag and in a normal JavaScript file or in a script tag:
function changeClass(this){
$('#nav li').attr("class","");
$(this).attr("class","current");
}
Replace the 'current' with the class name you want to use
3) it should already be set as current
4) use the :visited CSS selector to change what colour followed links look like eg:
a:visited{
color: #000000;
}
First of all you should set the event handler from a separate script, not from an onclick attribute. You don't repeat your code that way and have anything in one place. The HTML is also much cleaner.
Using jQuery it would be as easy as:
var menuLinks = jQuery( '#nav a' );
menuLinks.on( 'click' function() {
menuLinks.removeClass( 'active' );
$( this ).addClass( 'active' );
} );
You could also do that in plain JS, but using some library keeps you out of the trouble of browser incompatibilities.
Is it possible using JavaScript to dynamically remove just a few li elements from a ul, given the id's of the li elements?
UPDATE about the actual issue:
I've the following list.
<ul id="attributes" data-role="listview">
<li id="attrib01">Attribute1</li>
<li id="attrib02">Attribute2</li>
<li id="attrib03">Attribute3</li>
<li id="attrib04">Attribute4</li>
<li id="attrib05">Attribute5</li>
</ul>
After a ajax request/response, if a particular attribute is "undefined", I want to remove it from the list.
if(typeof data.attrib1 === "undefined")
$("#attrib01").remove();
I've made sure I'm receiving the correct ajax response. So, the problem now is, that when I remove attrib4, attrib[1-3] are being removed as well. Any idea why this might be happening?
Try
var elem = document.getElementById('id');
elem.parentNode.removeChild(elem);
If you get the element then find its parent then remove the element. from the parent as follows:
element = document.getElementById("element-id");
element.parentNode.removeChild(element);
It is necessary to go through the parent so this is unavoidable.
$('#id').remove() is the correct way to remove a single element. Note that element IDs must be unique in html, and that invocation must be wrapped in a DOM ready function.
This is a working example based on your html. It loops through all the list-items and removes the one whose id is not present in the data object:
var data = {
attrib01: "Number 1",
attrib02: "Number 2",
attrib04: "Number 4"
};
$(document).ready(function() {
$("ul > li").each(function() {
alert(this.id in data); //check if value is defined
if(!(this.id in data)) {
$(this).remove();
// This also works:
//$('#'+this.id).remove();
}
});
});
It is also possible to target and remove only a single element (Demo) by simply doing:
$(document).ready(function() {
$("#attrib04").remove();
});
Be careful with your IDs -- they must match exactly. attrib04 != attrib4
This will make the li elements invisible:
document.getElementById("id_here").style.visibility = "hidden";
Disclaimer: they will still be in the DOM
To remove elements from the DOM use JQuery's .remove() method:
$("#id_here").remove();
http://api.jquery.com/remove/
My navigation menu on header looks like this:
<ul id="nav">
<li id="home">
<a class="mainmenu" href="#">Link1</a>
</li>
<li>
<a class="mainmenu" href="#">Link2</a>
</li>
</ul>
and the same markup is used for the footer section and it's not working.
I have also a file called jscript.js which contains all the javascript for the website,
and I found this variable:
var navTarget = "ul#nav li a" //menu link to target
Also, if I remove for example the markup in the header sections the footer will work.
I've tried also to use .nav instead of #nav and I have the same problem.
The navigation menu is controlled by javascript, I don't post the code here because it's huge, for better understanding of how the navigation menu works look here
I've found this in the javascript:
//SET MENU ITEM IDs
$(navTarget).each(function(i){
i++
this.id = this.id +"_" +i ;
});
//MENU CLICK FUNCTION
$(navTarget).click(function() {
//ensure link isnt clickable when active
if ($(this).hasClass('active')) return false;
//get id of clicked item
activeNavItem = $(this).attr('id');
//call the page switch function
switchContent();
});
//CONTENT SWTICH FUNCTION
var switchContent = function (){
//set previous and next link & page ids
var PrevLink = $(navTarget+'.active')
$(PrevLink).removeClass('active');
var PrevId = $(PrevLink).attr('id');
//alert(PrevId)
var NextLink = $('#'+activeNavItem).addClass('active');
var NextId = activeNavItem
//alert(NextId);
From the looks of it, the JS code is using some CSS selector (like jquery's $ or dojo's dojo.query) that pulls in the DOM element target based on the value of navTarget, and then does something with it: turns it into a menu.
But its only doing it once.
You need to look at the JS and see where navTarget is used. Then it should be fairly easy to make it do the menu creation on all the results of $(navTarget) instead of just the first hit.
Also, you should only have on instance of an ID in your dom.
You can change this to a class instead:
var navTarget = "ul.nav li a"
And in the markup:
<div class='nav'>
But you will still have to look at the JS and make sure it functions against a set of targets returned by the CSS selector. That code is probably expecting just a single result and using just it: results[0].
You can only have one element of a given id on the page. So based on your description, it sounds like you have 2.
I don't know exactly how this script works, but you can try using classes instead.
<ul class="nav">
var navTarget = "ul.nav li a";
You would have to change your HTML and the JS navTarget selector string.
But there is also a good chance that your script may not support creating multiple menus at all. And if thats the case, you may need to fix that script or find a better one.
If the code for the footer really is identical to the header, that's the problem. An id should only be used for a single element in a page, and jQuery's selectors will only return the first. Meaning code like "ul#nav li a" only works on the header.
Easiest solution is to change the id's to classes, e.g.:
<ul class="nav">
... and change your jQuery to match that, e.g.:
var navTarget = "ul.nav li a";
Update: And (ignoring that this may end up turning into three duplicate posts), that fix is probably not enough at all, since other parts of the script may only work with a single menu.