Home>

How do I.append ()when I have a parent-child relationship and determine if there are children?

In the HTML below, I don't want to.append ()for "A, D, H, I" who have no children.

<div>
<ul>
  <li>
    <div>A (parent)<span>1</span><span>0</span></div>
  </li>
  <li>
    <div>B (parent)<span>2</span><span>0</span></div>
    <ul>
      <li>
        <div>C (child)<span>2.1</span><span>2</span></div>
      </li>
      <li>
        <div>D (grandchild)<span>2.1.1</span><span>2.1</span></div>
      </li>
      <li>
        <div>E (child)<span>2.2</span><span>2</span></div>
      </li>
      <li>
        <div>F (grandchild)<span>2.2.1</span><span>2.2</span></div>
      </li>
      <li>
        <div>G (great-grandchild)<span>2.2.1.1</span><span>2.2.1</span></div>
      </li>
      <li>
        <div>H (grandchild)<span>2.2.2</span><span>2.2</span></div>
      </li>
    </ul>
  </li>
  <li>
    <div>I (parent)<span>3</span><span>0</span></div>
  </li>
</ul>
</div>

It's a hard-to-understand structure, but the child of "Mr. B" has the value of Mr. B's.numas.parent-num. "C, E".

I wrote jQeury as a trial, but it was.append ()for everything.

$(". childrens li"). each (function () {
  var myNum = $(this) .find ('. num'). text ();
  if ($('. parent-num: contains (' + myNum + ')')) {
    $(this) .append ('↑ He has children');
  }
});


This is a sample of JSfidle.
https://jsfiddle.net/4hodcm05/

I want to make a distinction without changing the HTML. Can anyone do it?
(There is no discrimination based on the number of periods. Actually, it is a number without periods.)

  • Answer # 1

    Hello.

    How about correcting theifcondition as follows?

    Before correction:

    if ($('. parent-num: contains (' + myNum + ')')) {

    After correction:

    if ($('. parent-num: contains (' + myNum + ')'). length) {

    Sample:https://jsfiddle.net/jun68ykt/txcsLd73/1/

    The main point is that even if there is no element corresponding to$(some selector), use this in the condition ofifand useif ($(Some selector))means that$(some selector)evaluates to true and does not result in the intended decision.

    So, if you want to write a condition that "There is a match", it is determined by thelengthproperty is not 0.

    In addition, as shown below, an array with a length of 0 is also treated as true.

    $node -v
    v10.8.0
    $node
    >Boolean ([])
    true
    >if ([]) console.log ('hello');
    hello
    undefined
    >

    Thank you for your reference.


    Postscript

    Hello.
    It's been a while now, but it seems like you continue to add features and other things.

    Now, answer the following 1. and 2.

    Points to note about the code

    Errors caused by getParentNums using recursion

    1. Points to note about the code

    https://jsfiddle.net/psn5849w/97/

    I saw

    and figured out what kind of logic it was working on. The following points should be pointed out. (1) and (2) are fine tsukkomi, but (3) is a point where you feel like a problem will occur.

    (1) No s at the end of childrens

    <ul class ="childrens">childrensis deleted aschildren.

    (2) Array. Use array .includes (x) instead of indexOf (x)>= 0

    Use includes instead of indexOf to determine if an array contains any particular element.

    Before correction:

    if (parents.indexOf (my_post_num)>= 0) {


    After correction:

    if (parents.includes (my_post_num)) {
    (3) Regular expression correction

    Modify regular expression used to determine which child element to close when close is clicked

    Before correction:

    var child_ancestor_num = click_ancestor_num + '-' + click_post_num;

    After correction:

    var child_ancestor_num_pattern = new RegExp (`^ ${click_ancestor_num}-${click_post_num} (-\\ d +) * $`);
    As

    , check as follows.

    if (ancestor_num.match (child_ancestor_num_pattern)) {

    Before modification, ifchild_ancestor_numis"0-111-222",ancestor_numis"0-10-111-2229-76", the following judgment

    "0-10-111-2229-76" .match ("0-111-222");


    Will match and cause unintended behavior. You can avoid this by creating a regular expression as shown below.

    2. About errors caused by getParentNums using recursion
      

    When a comment is deleted, it becomes "too much recursion error!" due to recursion because the parent is deleted and cannot be found.

    I see. Perhaps this code is

      

    I cut and pasted the code that I taught or picked up all night

    As

    says, it is a masterpiece, so you can see what you want to do. However, there is a possibility that a certain post (post) may be deleted, and when I tried to cope with this, I wrote an error in the comment of 2018/09/01 01:22 Feelings about using [Pattern: A]:

      

    ・ ・ ・ ・ ・ The intuition is
      "If you don't write carefully, you'll probably write buggy code"

    It may be a situation that applies to

    .

    In other words, if it's easy to understand, if I and you were colleagues working in the same workplace,
    "Hello, w, so [pattern: ah] was quitting ~ w"
    and (in your mind) you might dis.

    If you write the node deletion/movement etc. by yourself, you will learn the algorithm and it will be fun, so you can also feel addicted, but if this is something If it is a part of the service to be put on the production server as a product, this kind of tree operation is just a DOM manipulation housework, so I feel better to get on the achievements of the previous programmer. (That is, it means adopting the [pattern: yes] that puts the parent-child relationship of posts on the parent-child relationship of DOM.)

    Even more wisely, you can dig into the basics of graph theory that underlies the tree, write your own code that recursively walks the tree nodes from top to bottom, or from the end nodes up, Reading other people's code and keeping the programming power just like you can write yourself if you want to do it, obviously when you want to get on the code you made, it's easy to get on I think that I would like to spend more time writing more important code.

    Nevertheless, I don't dislike the momentum of you who made a big break in [Pattern: Ah], although it was obviously hard.


    Postscript 2

    Still, if [Pattern: Yes] is followed, even if a certain post is deleted, it is only logically deleted without physically deleting the record in the post table of the backend database. In addition, I think that one post is to keep it from disappearing from the parent-child relationship tree as a post that appears as "This post has been deleted" on the screen display.

    And even in the future [Pattern: Yes], it seems to be difficult to have tree information in attributes such asmy_ancestor_numof HTML elements as strings separated by hyphens. So, shouldn't it be better to keep the post tree in a separate location from the DOM, depending on the data structure holding thetree?(I think it's an irresponsible idea).

    For example, the API that returns the tree information of the post including the reply in XML is prepared in the back end, the result of parsing the response that called this in the front end is the master data of the parent-child relationship, On the other hand, it is like using the JQuery selector to get the parent-child relationship of the post and reflect it in the DOM of the screen HTML.


    Postscript 3

    In any case, from here on, how to make a back-end posting table, how far the screen is rendered on the server side, and where to go from the front end? If you don't go into the details like this, you won't be able to comment accurately.

    Please do your best!

  • Answer # 2

    $('. num'). each (function (index, element) {
      if ($('. parent-num'). contents (). filter (function () {return this.nodeValue === element.textContent;}). length) {
        $(this) .closest ('div'). after ('↑ he has children') ';
      }
    });

Related articles