How can i change the padding o element by class name - javascript

im trying to change the padding of all the td in table.
somehow it doesnt work.
can you help ?
script ->
css ->
html ->

As Martin said in the comments ID's are unique selectors, so for apply style for td tag in script, you can use some thing like this:
<script>
let td = document.getElementsByTagName('td');
for (i = 0; i < td.length; i++) {
td[i].style.padding = "20px";
}
</script>
or change Id to class: strHtml += '<td class="curr-cell">'
and use document.getElementsByClassName('curr-cell') in above code.

Related

Having trouble selecting elements in CSS with elements created in JS

I created some divs with JS like so:
const container = document.querySelector('#container');
for(let i = 1; i < 17; i++) {
var row = document.createElement('div');
row.id = 'r' + i;
row.class = 'row';
container.appendChild(row);
for(let j = 1; j < 17; j++) {
var newDiv = document.createElement('div');
newDiv.id = 'c' + j;
newDiv.class = 'box';
newDiv.textContent = row.id;
row.appendChild(newDiv);
}
}
I'm trying to test the row divs by adding a border to each row class in css like so:
#row {
border: 1px solid green;
}
My question is how come the rows are not showing up with a green border? Am I able to select element from CSS file with elements created in JS?
I was expecting 16 boxes for each of the 16 div elements with class "row".
In the JS use className instead of class.
row.className = 'row'
In the CSS use a . (the # is an id selector)
.row {
border: 1px solid green;
}
You have two issues here...
The first issue is in css, to call a class to style in css you must use the . selector, so to select the row class and give it the style, you need to do this:
.row{
border: 1px solid green;
}
The second issue is in javascript.
JavaScript doesn't have a property called class for the DOM elements, but instead it has two other things to work woth the classes, one is the className property which is just a string that you must handle by yourself when you try to edit it.
And the code in this case will be like that':
row.className = 'row'
And the second is the classList object which has many useful methods like the add, remove, and the contains methods, that make it very easy to add, remove and check for foundation of multiple classes in javascript.
And the code in your case will be:
row.classList.add('row')
Then when you need to remove it you can just use this code:
row.classList.remove('row')
And anytime you try to do some code based on the class foundation, you can check for foundation using this code:
if( row.classList.contains('row') ) {
// Your code here
}
I hope i managed to help.

select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:
document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")
However, this code returns an error. The code should return the HTML element.
Does anybody know a way to achieve this? (vanilla JS preferred)
It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.
e.g
var div = document.getElementsByTagName('div');
for (var i=0;i<div.length;i++){
console.log(div[i].innerHTML)
if(div [i].innerHTML == 'hello world'){
var element = div[i].parentElement
console.log(element)
break;
}
}
You could use outerHTML to search for it, however this only works if the element has a parent element.
var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
el = els[i];
}
}
//Use the el variable for your element

Creating a table of divs

I want to create a 16*16 table in html that holds div container in each cell. I'm not sure to what degree I'm allowed to mix jquery and pure javascript but what I have is
$( document ).ready(function() {
var table = Doucument.getElementById('table');
for (var i = 0; i <16; i++) {
var row = table.insertRow(i);
for(var j = 0; j < 16; j++){
row.insertCell(i);
}
};
});
This is adding a row to my table and then adding 16 cells. However I'm not sure how to add the div element to each cell. Perhaps theres a simpler way to do this with jquery? I'm not so proficient in jquery
Change "Document" to "document", remove the loop indexes (i, j) from the insertRow() and insertCell methods, and capture the newly inserted cell so that you can populate it. I've set each div's ID to be a combination of row and cell number in the example below.
I should also point out that there are better ways to do this. Tables should only be used for displaying data that requires tables. Also, this kind of thing would ideally be done on the server side unless there's a reason for you to do it in JavaScript.
That being said, here is a working example using JavaScript:
HTML:
<table id="myTable"></table>
JavaScript:
$(document).ready(function () {
var table = document.getElementById('myTable');
for (var i = 0; i < 16; i++) {
var row = table.insertRow();
for (var j = 0; j < 16; j++) {
var cell = row.insertCell();
var id = 'r' + i + 'c' + j;
cell.innerHTML = '<div id="' + id + '">' + id + '</div>';
}
};
});
CSS (after reading your comment about controlling size):
#myTable TD DIV {
height: 30px;
width: 30px;
}
Demo: http://jsfiddle.net/BenjaminRay/ugm613zg/
Do you have a specific reason to create a "table" - it is frowned upon by UX and CSS experts. It is considered a better approach to consider creating a table-like layout using Div/Spans and CSS. There are frameworks available that can provide you this layout style out of the box.
One of the most popular ones is Bootstrap's Grid - and here are some layout examples - http://getbootstrap.com/examples/grid/. The benefit of using this approach instead of tables is that your layout will adjust better to screen size changes like say viewing on a mobile device (called responsive layout).
In the interest of full disclosure Bootstrap supports 12 columns out of the box - but modifications are available for 16 and 24 columns - How to use bootstrap with 16 or 24 columns.
This is a longer route but a better solution than tables overall.
And using jQuery, you could do the following.
function addElems(ele, howMany, append) {
var $items = $();
for (var i = 0; i < howMany; i++) {
var $ele = $("<" + ele + "/>");
typeof append !== "undefined" && $ele.append(append);
$items = $items.add($ele);
}
return $items;
}
var $table = $("#myTable").append("<tbody></tbody>");
var $trs = addElems('tr', 16);
$table.append($trs);
$table.find("tbody > tr").each(function() {
var $tds = addElems('td', 16, "<div>My Div</div>");
$(this).append($tds);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable"></table>

How to add 'style' in dynamically created table?

I have created table through DOM, now want to add style to that table but its not working.
code :
<script>
var nrCols=4;
var maxRows=10;
var nrRows=maxRows+1;
while(nrRows>maxRows)
{
nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
}
var root=document.getElementById('mydiv');
var tab=document.createElement('table');
var style=document.createElement('style');
style.setAttribute('background-color','red');
tab.appendChild(style);
tab.setAttribute('Border','1');
tab.className="mytable";
var tbo=document.createElement('tbody');
var tr1= document.createElement('tr');
var th1= document.createElement('th');
th1.appendChild(document.createTextNode('No.'));
var th2= document.createElement('th');
th2.appendChild(document.createTextNode('Surah.'));
tr1.appendChild(th1);
tr1.appendChild(th2);
tbo.appendChild(tr1);
var row, cell;
for(var i=0;i<nrRows;i++){
row=document.createElement('tr');
for(var j=0;j<nrCols;j++){
cell=document.createElement('td');
cell.appendChild(document.createTextNode('Allah'+' '+j))
row.appendChild(cell);
}
tbo.appendChild(row);
}
tab.appendChild(tbo);
root.appendChild(tab);
</script>
i have used style.setAttribute('background-color','red'); but no difference. how to fix it ?
Replace
var style=document.createElement('style');
style.setAttribute('background-color','red');
tab.appendChild(style);
with :
tab.style.backgroundColor = 'red';
All elements have a style attribute to which you can add the appropriate style values.
try to change the name of var style it might be causing the css style confusion, try this way
var menu = document.createElement("menu");
menu.style.backgroundColor = "#555";
Well, style is a HTML tag, when you create a element with that name it expects CSS info inside it. You maybe want this:
If you want to target the <th> element you should use this instead:
var th1 = document.createElement('th');
th1.style.backgroundColor = 'red';
Demo
it should be something like this
document.body.style.backgroundColor="#333333";
in your case
tab.style.backgroundColor="#333333"
Below code will create style tag
var css = 'table { background: red; }'
var style = document.createElement('style');
style.styleSheet.cssText = css;

How can I find the last visible <td> in a table?

I am using a table with one row and several <td>s inside it and am using hide/show on tds. Every td has a unique id.
Is there any way to recognize the last visible td from that table?
Yes, that's pretty trivial with jQuery
$('td:visible:last')
See this fiddle
In plain Javascript, I guess it should be something like this:
var els = document.getElementsByTagname('td');
for (var i = 0 ; i < els.length ; i++)
if (els[i].style && els[i].style.display != 'none')
last = els[i];

Categories

Resources