How do I style every last element of every line/row differently? - javascript

I've been trying to create a grid using
display:inline=block
I need to style every last element of every line/row differently. I tried
nth-child
nth-of-type
However, when I use that, it gets mixed up with my other grids. So how do I do it without adding new classes?

As far as i've seen from your code, you cannot use nth-child to achieve your goal. I will try to explain with an example:
you want the 4th and the 8th child of the section class="four" to be coloured red. In order to use nth-child or nth-of-type, you have to reference to children starting from their parent, i.e. body. So it's difficult to say what number in the list of body's children are the 4th and the 8th children of section class="four", and it's not flexible at all.
I think you are using it in the wrong way, something like section.four:last-child, which is not correct. Please check: w3schools link
Furthermore, nth-child and nth-of-type cannot be used with a selector but only with an element, so no way to do something like .four:nth-child (in the case you make a div with class="four" outside your sections).
So the only way, without adding more classes is jquery, like this:
$('.four').last().css('background-color', 'red');

In CSS3, if you associate every nth-child with a class of some type and every nth-of-type with another class use can style each one differently.
For instance,
<html>
<div class="nth-child">
//some code
</div>
<div class="nth-of-type">
//some code
</div>
</html>
Then in you CSS file you would do something similar to this:
.nth-child
{
//style rules
}
.nth-of-type
{
//style rules
}
I hope this is what you were looking for, without a posted example it is kinda hard to understand what you exactly mean. But if you want to us JS for this then you would create a JS function
obtain all elements in your page using "var elements= document.getElementsByClassName("nth-child")"
the you would loop through "elements.length" setting each element style to "none"

Related

Is there a way to apply css to part of the element?

I am looking for a way to apply new CSS to only part of the element.
For example. The original HTML looks like
<p>123456</p>
I want to make only 456 into bold.
Of course, I can do it by adding another tag into 456 like
<p>123<b>456</b></p>
But in my application, I do want not to change the original DOM structure. By adding a new tag, I changed the DOM structure.
To do that, I am thinking of adding new custom attribute to the existing tag like
<p data-wms="e-3">123456</p>
Here data-wms means that there are special part and e-3 means that from index 3 character (it is 4 here) to the end will have a special attribute (like bold in this example)
Now I have all the information about where to change inside the element.
But still, how can I do that with javascript without adding a tag, without changing dom.
Thanks
You can use the span element to do so, it's made specifically to handle inline styling while mantaining the overall structure.
An example would be:
<p>123<span class="bold-highlight">456</span></p>
Thanks to everyone's advice, I researched more, especially about nth-letter.
Though nth-letter is exactly what I want, I found that it is still just proposal, not implemented in any browser.
Thus, there is no way to applying different css letter by letter in one text element without embracing each letter with span tag at this moment (2021-March). I hope that there will be nth-letter in the near future.
I think that I have to re-design my project...
if it's a static page and you want to change a style for specific text in a specific tag like the following case
<p>11111</p>
<p>22222</p>
<p>33333</p>
<p>44444</p>
let's say you want just style the third element, you can change it by the following code using jQuery for sure you can use JavaScript but jQuery will help you to make your code shorter
$( "p:nth-child(3)" ).css("color","#f00");

Best practice in finding a DOM element

I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:
Find the element according to its class name, e.g $('.my-content')
Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()
However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?
If it's a specific element, supply it with an Id value and use that
to find it.
If it's a TYPE of element, use a class name.
Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.
A very good practice is to decouple HTML, CSS and JS.
When binding javascript to DOM elements you should use javascript selectors.
Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).
So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector
HTML
<div class="my-content js-toggle-element"></div>
JS
$('.js-toggle-element')
CSS
.my-content{ ... }
Plus, using Javascript Selectors:
makes HTML highly readable: you can easily find out what will happen to that element with that js class
allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all
<div class="my-content js-toggle-element"></div>
...
<div class="another-content-to-toggle js-toggle-element"></div>
Using jQuery will be much easiest way. Like this -
$( ".target" ).toggle();
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Reference - jQuery Toggle
If the class or the position of the element in DOM is changing then you can try
selecting it with the inner text
$("button:contains('buttontextgoeshere')")

how to toggle a div on click at different div?

I am trying to toggle a div by clicking on a different div. The only relation that two divs share is that they are inside the same div. I have a DIV class comment which holds DIV class button that is supposed to toggle DIV class box when clicked. The box DIV is also inside the comment DIV. I am trying to use jQuery(this).find(".box").toggle();, but it is not working. I am triggering it with $( ".button" ).click(function(). The script is currently at the bottom of my body.
Could anyone please tell me what am I doing wrong here? I've been playing around with the function for a while now, but with no luck at all. Thank you in advance for your replies.
JSFIDDLE here
HTML
<div class="comment">
<div class="button">
show/hide .box with text1
</div>
<div class="box">
text 1
</div>
</div>
<div class="comment">
<div class="button">
show/hide .box with text2
</div>
<div class="box">
text 2
</div>
<div>
jQuery
$( ".button" ).click(function() {
jQuery(this).find(".box").toggle();
});
You can use the jQuery selector .siblings() to re-write your function like this:
$( ".button" ).click(function() {
$(this).siblings().toggle();
});
Here's a working fiddle to demonstrate.
All you really need to do is this:
$(this).parent().find(".box").toggle();
In short, change:
jQuery(this).find(".box").toggle();
To ONE of the following lines:
$(this).parent('.comment').find(".box").toggle();
$(this).closest('.comment').find(".box").toggle();
$(this).siblings(".box").toggle();
Full Explanation:
The reason it's not working is due to the call. Let's break down your call and see what exactly it's doing.
First we see a simple jQuery selector. This tells jQuery to look for a div containing the class button. Keep in mind, jQuery makes use of any CSS selector. So selecting an item in jQuery is as simple as using it's CSS selector!
$( ".button" )
Next you are assigning an event. In this case, that event is click, meaning you're telling a div having the class button to do something every time it is clicked. Keep in mind, however, not including a callback function is an easy way to trigger this event as well.
$( ".button" ).click(function() {
Now this next line is where your mistake takes place.
jQuery(this).find(".box").toggle();
The first mistake is the use of jQuery. after you're already making use of it's short sign, $. You only need use the elongated name if you are using jQuery's noconflict because another JS library you include might use $. In other words, if $('.button') works and is a jQuery object when used, then you don't need to use jQuery.. See more about this here.
Now, that aside, we can look at jQuery(this) as $(this). Whenever you use $(this) in an Event's callback method, you're referring to the element that the event was tied too. That means that $(this) in your function refers to $('.button'). The problem here is that you then want it to find an inner element containing the class box. Well according to your HTML, that can't happen since .box is a sibling, it is not within the inner HTML of .button. Thus you need to make a different call before you can find .box.
There are actually several solutions here. No solution is more "correct" than another, just simply different and possibly causes a different amount of "time" to run. Now I went with what I saw as being the most simple in that it gives you control over the parent element which contains ALL relevant elements to this function. I'll talk about possible alternatives in a minute.
$(this).closest('.comment')
The above line simply tells .button:clicked to look for the first parent element that contains the class .comment. In other words, this won't find any children or siblings, it will only go up from the current element. This allows us to grab the block that contains all relevant elements and information and thus make maneuvers as needed. So, in the future, you might even use this as a variable in the function, such as:
$('.button').click(function(e) {
var container = $(this).closest('.comment');
Now you can find anything within this element block. In this case you want to find box and toggle it. Thus:
$(this).closest('.comment').find(".box").toggle();
// Or with our variable I showed you
container.find(".box").toggle();
Now, there are plenty of alternatives based on your HTML layout. This example I've given would be good even if .box was buried inside more elements inside .comment, however, given your exact HTML, we see that .button and .box are siblings. This means that you could make this call different entirely and get the same result using something like:
$(this).siblings(".box").toggle();
This will allow our currently clicked and selected button element to look for ANY and ALL siblings having class box. This is a great solution and simple if your HTML is that simple.
However, many times, for "comment" type setups, our HTML is not so simple, nor is it static. It's usually something loaded after the page load. This means our general assignment of .click will not work. Given your exact HTML and not knowing a static Parent ID, I would probably write your code as:
$(document).on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
What this does is allow for this click event to be assigned to ANY element containing .button for a class, whether loaded with page or even ten minutes after the page is up. However, the caveat often seen here is the assignment is placed on document. Should we assign a lot of events to document it could become quite convoluted and possibly slow down the client's browser. Not to mention the arguments held over all the other headaches this could cause. So here's my recommendation, make a static (loads with page, is a part of page's main HTML) loading area and do our dynamic assignment to that. For instance:
<div id"Comments"><!-- load comments --></div>
Then you can do the assignment as such:
$('#Comments').on('click', '.button', function(e) {
$(this).siblings('.box').toggle();
});
If you have any more questions, just comment!
Side Note .on is for jQuery versions 1.7+. If using older jQuery, use .live or .bind

Hide A element with CSS or Javascript

I have this element in my HTML page:
<a style="display:block;width:728px;height:90px;margin:0 auto;background:#EEE url('/_images/2011images/img_dotco_3.jpg') no-repeat top left; text-decoration:none;color:#000;" href="/domain-registration/dotco-overview.aspx?sourceid=bnrq2co728x90">
<span style="float:right;margin:5px 27px 0 0;width:110px;color:#FFF;text-align:center">
<span style="display:block;font-size:1em;text-align:center">NOW ONLY</span>
<strong style="display:block;font-size:1.6em;text-align:center"><!-- START TAG // Co_RegisterPrice_TLD -->
<span class="Tag_Co_RegisterPrice_TLD"><strong>$35.70</strong>/yr</span>
<!-- End TAG // Co_RegisterPrice_TLD --></strong>
</span>
</a>
I need to hide it with CSS or Javascript. CSS would be the best scenario but Javascript is OK as well.
The fact is that I cannot edit the HTML code at all, so I have no way to delete this item directly. Also this is not parent of any other HTML element, so I do not find an easy way to hide it with CSS.
Also I need to hide this A element even if the background image changes or the link changes, in fact it's not always the same.
I reported all the available HTML.
Here is an example http://subdir.co/help-center/default.aspx
It's the top banner there.
Let me know how to hide it from the page. Thanks.
Try with jQuery:
$('a[href^="/domain-registration/dotco-overview.aspx?sourceid"]').hide();
This hides the a tag with a href attribute starting with /domain-registration/dotco-overview.aspx?sourceid.
Use:
document.getElementById('yourElementId').display=none;
You can traverse the dom tree from the class "Tag_Co_RegisterPrice_TLD" to find the A tag which you can then hide.
If you need to do additional logic then you can access the text (e.g. price/title/url) before deciding to hide.
Use jQuery if raw javascript is to much for you.
Since you cannot change the HTML code, you can't add an identifier to the element in order to select and manipulate it.
But you can use jQuery to select the first 'a' element, and set the 'display' property to 'none'.
I think something like this should do:
$('a:first').css("display","none");
You could try it with css:
a[style][href] {
display: none !important;
}
i think adding class or making some rule for css selector woudn't work, because definition in attribute of the elements overrides another style definition.
It will be easy if you use some javascript library for dom manipulating for example jQuery.
after that you can write something like
$(".sCntSub3 > a").hide()
you can try finding element from browser console. It is easy way how to verify you choose right element
jsFiddle Classname Method DEMO
jQuery via Classname: In this method we "look inside" the anchor for clues.
$(document).ready(function () {
// To disable the line below, just comment it out just like this line is.
$('.Tag_Co_RegisterPrice_TLD').closest('a').hide();
});
jsFiddle ID Method DEMO
jQuery via ID: This time, we don't look inside since anything can change. We now use a div reference!
$(document).ready(function () {
// To disable the line below, just comment it out just like this line is.
// No matter the unique ID code in front of MasterUpdatePanel Div, it will always be matched.
$('[id$="MasterUpdatePanel"]').next('a').hide();
});
Shown here is a Firefox Screenshot of the HTML Page. Notice the Div ID contains ctl00_MasterUpdatePanel. The letters, numbers, and underscore in front of that may change, but not this keyword. Therefore, a match of the "ending part" of the id works!

Change name of a html class

I use a website, which shows information i have no use for, so i tried to hide some of it with Stylish, an addon for Chrome to insert custom CSS.
I will try to explain better.
<div class="splitscreenleft"> <div id="toplevel"
<div class="splitscreenleft"> <div id="coursesection"
I want to hide one of those. Everything above splitscreenleft is the same on both. So the only difference is the div id below.
I must somehow hide one of the two classes based on the name of the div below it i think.
Any solutions to this problem?
You should be able to do this either via CSS or JavaScript.
You probably don't even need to search the children out. You can probably just pick the first or second one that appears on the page and style that. To do via CSS, use the first-of-type selector - http://www.w3.org/TR/css3-selectors/#first-of-type-pseudo
div.splitscreenleft:first-of-type { display: none; }
To do this via JavaScript, you can find the parent object and then hide it:
document.getElementById("toplevel").parentNode.style.display = 'none';
You should be able to do it similarly in jQuery:
$(".splitscreenleft:has(#toplevel)").hide();​
This can be accomplish by CSS, using structural pseudo-classes alone:
.parentClassName .className :nth-child(n) { display: none; }
Where n is the element you want to select. In your case you have two elements with the same class. To hide the first one, just replace n with 1, or 2 to hide the second one. You get the idea.
If you can't get access to jQuery with JS (haven't tried in chrome), you could always say
$('#topLevel').parent().hide();
the code below can change the class you defined in style sheet.
document.getElementById("testPara").className = "yourclass";

Categories

Resources