1

Sorry for the noob question as I just picked up javascript today.

I'm trying to create and delete div's with javascript buttons, and I have that working fairly well.

However when I delete,for example, div #7, out of div 1-8 I need the text to change so that it doesn't look like

number: 1
number: 2
number: 3
number: 4
number: 5
number: 6
number: 8

This code adds the div at the end of the containing div xbox

d1.insertAdjacentHTML('beforeend', '<div class="xbox" id ="xbox1'+numItems+'">Number:  '+countBox()+'</div>

this code counts the amount of boxes already

    function countBox()
{
    var numItems = $('.Cbox').length;
    return numItems;

}

I've thought about just taking the div and setting the inner-html. But I figured I'd see if there is a better way to force the code to update the variable.

3
  • 1
    Could you make a jsfiddle for us? Commented Mar 11, 2014 at 22:14
  • Why two different classes, you're inserting xbox boxes, but counting Cbox boxes ? Commented Mar 11, 2014 at 22:15
  • I cant get jsfiddle to work :P jsfiddle.net/JygnV/1 Commented Mar 11, 2014 at 22:29

3 Answers 3

1

So basically update the text of all the elements so they are in numbered order again after one is removed.

The numItems variable uses the length, so that's not an issue.

To update the text of the all the boxes you could do

$('.xbox').text(function(i) {
    return 'number: ' + (i+1);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Couldnt have put it better myself.
So then would I call this somewhere?
0
  1. add text to your divs
  2. add onclick functions and pass what div i.e., onclick="myFunction(0)"
  3. Update the div text

    document.getElementById('yourID').innerHTML = "new text!";

full example

HTML

<div id="div 1" onClick('update(0)');>some text</div>
<div id="div 2" onClick('update(1)');>some text</div>
<div id="div 3" onClick('update(2)');>some text</div>

* JavaScript *

function update(column){
    //max number of divs from your example would be 8
    for(var i = column; i < MAX_NUMBER_DIV_HERE; i++){
        document.getElementById('div ' + i).innerHTML = i + "";
    }
}

Comments

0

Maybe you could use an ol instead with a custom format? (More info)

Or if there is a small amount of numbers, nth-child with text-before?

#group div:nth-child(1):before { 
  content: "number: 1";
}

#group div:nth-child(2):before { 
  content: "number: 2";
}

Legacy support is not very good in both cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.